package com.mzj.saas.mservice.lock.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.haixiaoke.saas.repository.exception.BizException;
import com.haixiaoke.saas.repository.pojo.HousingAllocation;
import com.haixiaoke.saas.repository.pojo.Order;
import com.haixiaoke.saas.repository.pojo.OrderPasswordRecord;
import com.haixiaoke.saas.repository.service.IOrderPasswordRecordService;
import com.haixiaoke.saas.repository.service.IOrderService;
import com.haixiaoke.saas.repository.util.GsonUtil;
import com.mzj.saas.commons.*;
import com.mzj.saas.commons.enums.LockAuthTypeEnum;
import com.mzj.saas.commons.enums.RemainingStatusEnum;
import com.mzj.saas.commons.enums.UserLoginTypeEnum;
import com.mzj.saas.commons.enums.XzLockOperatorTypeEnum;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.config.sms.SmsConfig;
import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.entity.BacklogItemCard;
import com.mzj.saas.mservice.backlog.repository.BacklogItemCardRefRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.community.entity.Community;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.currency.service.LockCurrencyService;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.entity.UserDepartmentRef;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.repository.LockFrozenRepository;
import com.mzj.saas.mservice.house.vo.HouseVO;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.*;
import com.mzj.saas.mservice.lock.vo.*;
import com.mzj.saas.mservice.lockManager.entity.SmartLockBrand;
import com.mzj.saas.mservice.lockManager.repository.SmartLockBrandRepository;
import com.mzj.saas.mservice.oss.service.OSSService;
import com.mzj.saas.mservice.property.entity.HouseRemaining;
import com.mzj.saas.mservice.property.entity.HouseRemainingRelation;
import com.mzj.saas.mservice.property.entity.MatchUserHouse;
import com.mzj.saas.mservice.property.repository.CommunityHouseUserRepository;
import com.mzj.saas.mservice.property.repository.HouseRemainingRelationRepository;
import com.mzj.saas.mservice.property.repository.HouseRemainingRepository;
import com.mzj.saas.mservice.property.repository.MatchUserHouseRepository;
import com.mzj.saas.mservice.smartlock.service.SmartLockBrandService;
import com.mzj.saas.mservice.smartlock.service.tianwanghulian.SmartLockTWHlService;
import com.mzj.saas.mservice.smartlock.service.youdian.SmartLockYdService;
import com.mzj.saas.mservice.smartlock.vo.SmartLockFingerprintVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import com.mzj.saas.mservice.smartlock.vo.yaluete.YltAuthorizationVO;
import com.mzj.saas.mservice.sms.service.SmsService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.mservice.sys.utils.SqlUtils;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class LockAppService {
    private static final Logger log = LoggerFactory.getLogger(LockAppService.class);

    private static final String AUTH_ORDER = " ORDER BY l.operator_time DESC";
    private static final String LOG_ORDER = " ORDER BY l.open_time DESC";
    private static final String FROZEN_ORDER = " ORDER BY l.operation_time DESC";
    private static final String SQL_PAGE = " LIMIT ? OFFSET ?";

    @Autowired
    private RedisService redisService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private SmartLockBrandService smartLockBrandService;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private LockFrozenRepository lockFrozenRepository;
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;
    @Autowired
    private SmartLockFingerprintRepository smartLockFingerprintRepository;
    @Autowired
    private SmartLockBrandRepository smartLockBrandRepository;
    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SmsService smsService;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private LockFrozenSetRepository lockFrozenSetRepository;
    @Autowired
    private SmartLockBleRepository smartLockBleRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Autowired
    private MatchUserLockAuthorRepository matchUserLockAuthorRepository;
    @Autowired
    private MatchUserHouseRepository matchUserHouseRepository;
    @Autowired
    private HouseLockFrozenLogRepository houseLockFrozenLogRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;// 待办事项
    @Autowired
    private BacklogItemCardRefRepository backlogItemCardRefRepository;//
    @Autowired
    private LockCurrencyService lockCurrencyService;// 智能锁通用接口
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private HouseRemainingRepository houseRemainingRepository;
    @Autowired
    private HouseRemainingRelationRepository houseRemainingRelationRepository;
    @Autowired
    private HouseRemainingPostponeRepository houseRemainingPostponeRepository;
    @Autowired
    private SmartLockTWHlService smartLockTWHlService;
    @Autowired
    private SmartLockFaceRepository smartLockFaceRepository;
    @Autowired
    private SmartLockYdService smartLockYdService;
    @Value("${ali.oss.bucket.url}")
    private String ossBucketUrl;
    @Autowired
    private OSSService ossService;
    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private IOrderPasswordRecordService iOrderPasswordRecordService;

    /**
     * 智能锁列表
     *
     * @param accessToken   权限鉴定
     * @param houseId       公租房id
     * @param roomNumber    房号
     * @param mechineStatus 设备状态:0未激活 1正常 2冻结
     * @param pageNumber    当前页
     * @param pageSize      页数
     * @return
     */
    public ResultBean<ApiData<LockListVO>> lockList1(String accessToken, String search, String name, String mac,
                                                     String houseId, String communityId, Long buildId, Long unitId, String roomNumber, String orgName,
                                                     String matchUserName, Integer mechineStatus, Integer pageNumber, Integer pageSize) {
        ResultBean<ApiData<LockListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<LockListVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            Integer loginType = tokenRedisVo.getLoginType();
            Integer flag = tokenRedisVo.getFlag();

            String phone = null;
            if (flag == 1) {
                User user = userRepository.findById(userId);
                phone = user.getMobile();
            } else {
                AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
                phone = appUser.getPhone();
            }

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");

            if (loginType == 1) {
                DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                if (hierarchy == null) {
                    return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                }
                List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId());
                List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

                // 1、政府机构，根据区域标签所对应区域id查
                Long areaId = null;
                String areaTag = "province_id";
                if (enterpriseTagIds.contains(3L)) {
                    Long areaTagId = hierarchy.getTagId();// 区域标签
                    if (areaTagId == null) {
                        return ResultBean.failedResultWithMsg("机构所对应区域标签为空");
                    }

                    if (areaTagId == 1) {
                        areaTag = "province_id";
                    } else if (areaTagId == 2) {
                        areaTag = "city_id";
                    } else if (areaTagId == 3) {
                        areaTag = "district_id";
                    } else if (areaTagId == 4) {
                        areaTag = "street_id";
                    } else if (areaTagId == 5) {
                        areaTag = "community_id";
                    }
                    areaId = hierarchy.getAreaId();// 区域id
                }

                // 2、产权单位，根据orgId
                Long hierarchyOrgId = null;
                if (enterpriseTagIds.contains(2L)) {
                    hierarchyOrgId = hierarchy.getOrgId();
                }

                // 3、物业，查已绑定该物业的小区
                List<String> residenceCommunityIds = new ArrayList<>();
                if (enterpriseTagIds.contains(4L)) {
                    List<Community> communities = communityRepository.findByOrgIdAndStatus(enterpriseId, 1);
                    residenceCommunityIds = communities.stream().map(Community::getId).distinct().collect(Collectors.toList());// 小区id
                }

                where.append(" and (h." + areaTag + " = ? or l.org_id = ? or l.community_id in ");
                args.add(areaId);
                args.add(hierarchyOrgId);
                if (!residenceCommunityIds.isEmpty()) {
                    where.append(SqlUtils.foreachIn(residenceCommunityIds.size()) + ")");
                    args.addAll(residenceCommunityIds);
                } else {
                    where.append("(null))");
                }
            } else {
                List<SmartLockAuth> authList = smartLockAuthRepository.findOrgLockAuth(userId, phone);
                List<Long> lockIds = authList.stream().map(SmartLockAuth::getLockId).distinct().collect(Collectors.toList());
                where.append(" and l.id in ");
                if (!lockIds.isEmpty()) {
                    where.append(SqlUtils.foreachIn(lockIds.size()));
                    args.addAll(lockIds);
                } else {
                    where.append("(null)");
                }
            }

            // 公租房单位锁
            where.append(" and h.house_nature = 1 and l.bind_type = 1 and l.bind_status = 1");

            if (StringUtils.isNotBlank(search)) {
                where.append(" AND (l.`community_name` LIKE ? OR l.`match_user_name` LIKE ? OR l.`org_name` LIKE ?)");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
            }
            if (StringUtils.isNotBlank(name)) {
                where.append(" AND l.`name` LIKE ?");
                args.add("%" + name + "%");
            }
            if (StringUtils.isNotBlank(mac)) {
                where.append(" AND l.`mac` LIKE ?");
                args.add("%" + mac + "%");
            }
            if (StringUtils.isNotBlank(houseId)) {
                where.append(" AND l.`house_id` LIKE ?");
                args.add("%" + houseId + "%");
            }
            if (StringUtils.isNotBlank(communityId)) {
                where.append(" AND l.`community_id` = ?");
                args.add(communityId);
            }
            if (buildId != null) {
                where.append(" AND l.`build_id` = ?");
                args.add(buildId);
            }
            if (unitId != null) {
                where.append(" AND l.`unit_id` = ?");
                args.add(unitId);
            }
            if (StringUtils.isNotBlank(roomNumber)) {
                where.append(" AND l.`room_number` = ?");
                args.add(roomNumber);
            }
            if (StringUtils.isNotBlank(orgName)) {
                where.append(" AND l.`org_name` LIKE ?");
                args.add("%" + orgName + "%");
            }
            if (StringUtils.isNotBlank(matchUserName)) {
                where.append(" AND l.`match_user_name` LIKE ?");
                args.add("%" + matchUserName + "%");
            }
            if (mechineStatus != null) {
                where.append(" AND l.`mechine_status` = ?");
                args.add(mechineStatus);
            }


            // 总记录数
            Long total = jdbcTemplate.queryForObject("SELECT count(1) FROM `saas_smart_lock` l left join `saas_house` h on l.`house_id` = h.id" + where, args.toArray(),
                    Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<LockListVO> lockList = jdbcTemplate
                    .query("SELECT l.id as lockId,l.brand_id as brandId,l.name,l.mac,l.house_id AS houseId,l.community_name AS communityName,l.build_name AS buildName,l.unit_name AS unitName,\n"
                            + "l.room_number AS roomNumber,l.match_user_id AS matchUserId,l.match_user_name AS matchUserName,l.org_name AS orgName,l.oauth_number AS oauthNumber,l.mechine_status as mechineStatus,\n"
                            + "l.reason,l.operator_time AS operatorTime FROM `saas_smart_lock` l left join `saas_house` h on l.`house_id` = h.id" + where
                            + AUTH_ORDER + SQL_PAGE, new BeanPropertyRowMapper<>(LockListVO.class), args.toArray());

            // 总授权人数
            List<Long> lockIds = lockList.stream().map(LockListVO::getLockId).distinct().collect(Collectors.toList());
            List<Map<String, Object>> maps = jdbcTemplate.queryForList("SELECT lock_id AS lockId,COUNT(1) AS oauthCount FROM saas_smart_lock_auth WHERE lock_id IN "
                    + SqlUtils.foreachIn(lockIds.size()) + " AND bind_type = 0 GROUP BY lock_id", lockIds.toArray());

            for (LockListVO vo : lockList) {
                String operatorTime = vo.getOperatorTime();
                vo.setOperatorTime(operatorTime == null ? "" : DateUtils.format(operatorTime, DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));

                // 总授权人数
                for (Map map : maps) {
                    long lockId = Long.parseLong(map.get("lockId").toString());
                    int oauthCount = Integer.parseInt(map.get("oauthCount").toString());
                    if (vo.getLockId() == lockId) {
                        vo.setOauthCount(oauthCount);
                    }
                }

                // 单位标识
                if (loginType == 1) {
                    vo.setOrgFlag(1);
                } else {
                    vo.setOrgFlag(0);
                }
            }

            apiData.setData(lockList);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockAppService lockList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    /**
     * 授权用户列表
     *
     * @param accessToken 权限鉴定
     * @param houseId     公租房id
     * @return
     */
    public ResultBean<LockAuthData<LockAuthVO>> lockAuth(String accessToken, String houseId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Integer loginType = tokenRedisVo.getLoginType();
            // 登录场景标识：1.PC端登录 2.APP登录
            Integer flag = tokenRedisVo.getFlag();
            String phone = tokenRedisVo.getPhone();
            if (loginType == 1) {
                User user = userRepository.findById(userId);
                phone = user.getMobile();
            } else {
                AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
                phone = appUser.getPhone();
            }

            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultOfParamWithMsg("公租房id为空");
            }

            List<SmartLock> smartLocks = smartLockRepository.findByHouseId(houseId);
            if (smartLocks.isEmpty()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = smartLocks.get(0);
            Integer houseType = smartLock.getHouseType();

            LockAuthData<LockAuthVO> data = new LockAuthData<>();
            data.setLockId(smartLock.getId());
            data.setMechineStatus(smartLock.getMechineStatus());
            data.setAuthStatus(0);
            data.setReason(smartLock.getMechineStatus() != null && smartLock.getMechineStatus() == 1 ? null : smartLock.getReason());
            List<SmartLockAuth> authList = smartLockAuthRepository.findByHouseIdAndBindType(houseId, 0);
            List<LockAuthVO> list = new ArrayList<>();
            Integer authState = 2;
            for (SmartLockAuth auth : authList) {
                // 获得 关系标签名称
                List<House> byIdAndStatus = houseRepository.findByIdAndStatus(houseId, 1);
                LockAuthVO vo = new LockAuthVO();
                // 设置合租房屋号和合租房屋子房屋id
                if (byIdAndStatus.get(0).getMatchType() == 2) {
                    vo.setRoomNumber(auth.getRoomNumber());
                    vo.setSubHouseId(auth.getSubHouseId());
                }
                vo.setLockAuthId(auth.getId());
                vo.setRelationTagName(auth.getRelationTag() != null ? relationTagName(houseType, auth.getRelationTag()) : null);// 关系标签名称
                vo.setHouseType(houseType);
                vo.setLockId(auth.getLockId());
                if (houseType == 1) { // 公租房
                    if (auth.getUserType() == 1) {
                        vo.setUserType("户主");
                    } else if (auth.getUserType() == 2) {
                        vo.setUserType("同住人");
                    } else if (auth.getUserType() == 3) {
                        vo.setUserType("房屋管理员");
                    } else {
                        vo.setUserType("房管员");
                    }
                } else {
                    if (auth.getUserType() == 1) {
                        vo.setUserType("承租人");
                    } else if (auth.getUserType() == 2) {
                        vo.setUserType("同住人");
                    } else if (auth.getUserType() == 3) {
                        vo.setUserType("房屋管理员");
                    } else {
                        vo.setUserType("房管员");
                    }
                }
                vo.setRelationTag(auth.getRelationTag());
                vo.setUserName(auth.getUserName());
                vo.setMobile(auth.getMobile());
                vo.setPwdStatus(auth.getPwdStatus());
                vo.setFingerprintStatus(auth.getFingerprintStatus());
                vo.setCardStatus(auth.getCardStatus());
                vo.setCpuStatus(auth.getCpuStatus());
                vo.setBleStatus(auth.getBleStatus());
                vo.setFaceStatus(auth.getFaceStatus());
                if (userId.equals(auth.getAuthorUserId() == null ? "" : auth.getAuthorUserId()) || phone.equals(auth.getMobile())) {
                    vo.setFlag(1);
                } else {
                    vo.setFlag(0);
                }
                list.add(vo);


                if (NumberUtil.equals(authState,auth.getFaceStatus())||NumberUtil.equals(authState, auth.getCardStatus()) ||
                        NumberUtil.equals(authState, auth.getCardStatus())  || NumberUtil.equals(authState, auth.getBleStatus()) ||
                        NumberUtil.equals(authState, auth.getFingerprintStatus())  || NumberUtil.equals(authState, auth.getPwdStatus())){
                    vo.setFrozenState(1);
                }else {
                    vo.setFrozenState(0);
                }
            }
            // 承租人能看到全部信息，同住人只能看到自己,企业用户不做限制
            if (flag != 1) {
                List<SmartLockAuth> byAuthorUserId = smartLockAuthRepository.findByAuthorUserId(userId);
                Integer userType1 = 0;
                if (CollectionUtil.isNotEmpty(byAuthorUserId)) {

                    userType1 = byAuthorUserId.get(0).getUserType();
                }
                if (userType1 == 0) {
                    for (int i = list.size() - 1; i >= 0; i--) {
                        String mobile = list.get(i).getMobile();
                        if (!phone.equals(mobile)) {
                            list.remove(i);
                        }
                    }
                    data.setData(list);
                    return ResultBean.successfulResult(data);
                }
                if (userType1 != null && userType1 == 2) {
                    for (int i = list.size() - 1; i >= 0; i--) {
                        String mobile = list.get(i).getMobile();
                        if (!phone.equals(mobile)) {
                            list.remove(i);
                        }
                    }
                }
            }

            data.setData(list);

            // 授权状态，有其中一种授权就是已授权状态
            for (LockAuthVO vo : list) {
                if (vo.getPwdStatus() == 1 || vo.getFingerprintStatus() == 1 || vo.getCardStatus() == 1
                        || vo.getCpuStatus() == 1 || vo.getBleStatus() == 1) {
                    data.setAuthStatus(1);
                    break;
                }
            }

            return ResultBean.successfulResult(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 智能锁开门记录
     *
     * @param accessToken 权限鉴定
     * @param lockId      智能锁id
     * @param openType    开门类型：1外开门 2内开门
     * @param search      搜索条件
     * @param date        日期
     * @param pageNumber  当前页数
     * @param pageSize    页数
     * @return
     */
    public ResultBean<ApiData<LockOpenLogVO>> lockOpenLog(String accessToken, Long lockId, Integer openType,
                                                          String search, String date, String matchUserName, String communityId, Long buildId, Long unitId,
                                                          String roomNumber, String beginDate, String endDate, Integer pageNumber, Integer pageSize) {
        ResultBean<ApiData<LockOpenLogVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<LockOpenLogVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            Integer loginType = tokenRedisVo.getLoginType();

            if (openType == null) {
                return ResultBean.failedResultOfParamWithMsg("开门类型不存在");
            }

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            // 锁已删除的不展示开门记录
            where.append(" where s.id is not null");

            if (lockId != null) {
                where.append(" and l.lock_id = ?");
                args.add(lockId);
            } else {
                if (loginType == 1) {
                    DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                    if (hierarchy == null) {
                        return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                    }
                    List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId());
                    List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

                    // 1、政府机构，根据区域标签所对应区域id查
                    Long areaId = null;
                    String areaTag = "province_id";
                    if (enterpriseTagIds.contains(3L)) {
                        Long areaTagId = hierarchy.getTagId();// 区域标签
                        if (areaTagId == null) {
                            return ResultBean.failedResultWithMsg("机构所对应区域标签为空");
                        }
                        if (areaTagId == 1) {
                            areaTag = "province_id";
                        } else if (areaTagId == 2) {
                            areaTag = "city_id";
                        } else if (areaTagId == 3) {
                            areaTag = "district_id";
                        } else if (areaTagId == 4) {
                            areaTag = "street_id";
                        } else if (areaTagId == 5) {
                            areaTag = "community_id";
                        }
                        areaId = hierarchy.getAreaId();// 区域id
                    }
                    // 2、产权单位，根据orgId
                    Long hierarchyOrgId = null;
                    if (enterpriseTagIds.contains(2L)) {
                        hierarchyOrgId = hierarchy.getOrgId();
                    }
                    // 3、物业，查已绑定该物业的小区
                    List<String> residenceCommunityIds = new ArrayList<>();
                    if (enterpriseTagIds.contains(4L)) {
                        List<Community> communities = communityRepository.findByOrgIdAndStatus(enterpriseId, 1);
                        residenceCommunityIds = communities.stream().map(Community::getId).distinct().collect(Collectors.toList());// 小区id
                    }

                    where.append(" and ( h." + areaTag + " = ? or s.org_id = ? or s.match_user_id = ? or s.community_id in ");
                    args.add(areaId);
                    args.add(hierarchyOrgId);
                    args.add(userId);
                    if (!residenceCommunityIds.isEmpty()) {
                        where.append(SqlUtils.foreachIn(residenceCommunityIds.size()) + ")");
                        args.addAll(residenceCommunityIds);
                    } else {
                        where.append("(?) )");
                        args.add(null);
                    }
                } else {
                    where.append(" and s.match_user_id = ?");
                    args.add(userId);
                }
            }

            where.append(" and l.open_type = ?");
            args.add(openType);

            if (!StringUtils.isBlank(search)) {
                where.append(
                        " AND  l.open_user_name  LIKE ? OR s.`community_name` LIKE ? OR s.build_name LIKE ? OR s.unit_name LIKE ?");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
            }
            if (StringUtils.isNotBlank(date)) {
                where.append(" and l.open_time >= ? AND l.open_time < ?");
                args.add(date);
                args.add(DateUtils.getAddDaysTime(date, DateUtils.FORMAT_DATE_8, 1));
            }
            if (StringUtils.isNotBlank(matchUserName)) {
                where.append(" AND l.open_user_name LIKE ?");
                args.add("%" + matchUserName + "%");
            }
            if (StringUtils.isNotBlank(communityId)) {
                where.append(" AND s.`community_id` = ?");
                args.add(communityId);
            }
            if (buildId != null) {
                where.append(" AND s.`build_id` = ?");
                args.add(buildId);
            }
            if (unitId != null) {
                where.append(" AND s.`unit_id` = ?");
                args.add(unitId);
            }
            if (StringUtils.isNotBlank(roomNumber)) {
                where.append(" AND s.`room_number` = ?");
                args.add(roomNumber);
            }
            if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
                where.append(" and l.open_time >= ? AND l.open_time < ?");
                args.add(beginDate);
                args.add(DateUtils.getAddDaysTime(endDate, DateUtils.FORMAT_DATE_8, 1));
            }

            // 总记录数
            Long total = jdbcTemplate.queryForObject(
                    "SELECT count(1) FROM `saas_house_lock_open_log` l LEFT JOIN saas_smart_lock s ON l.lock_id = s.id left join saas_house h on l.house_id = h.id"
                            + where,
                    args.toArray(), Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<LockOpenLogVO> list = jdbcTemplate.query(
                    "select s.match_user_name as matchUserName,l.open_mode as openMode, l.open_user_name as openUserName, s.community_id as communityId,s.community_name as communityName,\n"
                            + "s.build_id as buildId,s.build_name as buildName,s.unit_id as unitId,s.unit_name as unitName,s.room_number as roomNumber,l.open_time as openTime\n"
                            + "from `saas_house_lock_open_log` l LEFT JOIN saas_smart_lock s ON l.lock_id = s.id left join saas_house h on l.house_id = h.id"
                            + where + LOG_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(LockOpenLogVO.class), args.toArray());

            for (LockOpenLogVO vo : list) {
                vo.setOpenTime(
                        DateUtils.format(vo.getOpenTime(), DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));
                Integer openMode = vo.getOpenMode();
                if (openMode == 0) {
                    vo.setOpenModeName("普通密码");
                } else if (openMode == 1) {
                    vo.setOpenModeName("动态密码");
                } else if (openMode == 5) {
                    vo.setOpenModeName("次数密码");
                } else if (openMode == 9) {
                    vo.setOpenModeName("管理员密码");
                } else if (openMode == 10) {
                    vo.setOpenModeName("一键开门");
                } else if (openMode == 11) {
                    vo.setOpenModeName("普通卡开门");
                } else if (openMode == 21) {
                    vo.setOpenModeName("指纹开门");
                } else if (openMode == 25) {
                    vo.setOpenModeName("蓝牙开门");
                } else if (openMode == 30) {
                    vo.setOpenModeName("钥匙开门");
                } else if (openMode == 32) {
                    vo.setOpenModeName("人脸开门");
                } else {
                    vo.setOpenModeName("虹膜开门");
                }
            }

            apiData.setData(list);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockAppService lockOpenLog Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    /**
     * 解冻/冻结记录
     *
     * @param accessToken 权限鉴定
     * @param lockId      智能锁id
     * @param type        操作类型:0解冻 1冻结
     * @param beginDate   开始时间
     * @param endDate     结束时间
     * @param pageNumber  当前页
     * @param pageSize    页数
     * @return
     */
    public ResultBean<ApiData<LockFrozenVO>> frozenOrUnfrozenLog(String accessToken, Long lockId, String matchUserName,
                                                                 String communityId, Long buildId, Long unitId, String roomNumber, Integer type, String beginDate,
                                                                 String endDate, Integer pageNumber, Integer pageSize) {
        ResultBean<ApiData<LockFrozenVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<LockFrozenVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            Integer loginType = tokenRedisVo.getLoginType();

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();

            // 锁已删除的不展示冻结解冻记录
            where.append(" where s.id is not null");

            if (lockId != null) {
                where.append(" and l.lock_id = ?");
                args.add(lockId);
            } else {
                if (loginType == 1) {
                    DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                    if (hierarchy == null) {
                        return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                    }
                    List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId());
                    List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

                    // 1、政府机构，根据区域标签所对应区域id查
                    Long areaId = null;
                    String areaTag = "province_id";
                    if (enterpriseTagIds.contains(3L)) {
                        Long areaTagId = hierarchy.getTagId();// 区域标签
                        if (areaTagId == null) {
                            return ResultBean.failedResultWithMsg("机构所对应区域标签为空");
                        }
                        if (areaTagId == 1) {
                            areaTag = "province_id";
                        } else if (areaTagId == 2) {
                            areaTag = "city_id";
                        } else if (areaTagId == 3) {
                            areaTag = "district_id";
                        } else if (areaTagId == 4) {
                            areaTag = "street_id";
                        } else if (areaTagId == 5) {
                            areaTag = "community_id";
                        }
                        areaId = hierarchy.getAreaId();// 区域id
                    }
                    // 2、产权单位，根据orgId
                    Long hierarchyOrgId = null;
                    if (enterpriseTagIds.contains(2L)) {
                        hierarchyOrgId = hierarchy.getOrgId();
                    }
                    // 3、物业，查已绑定该物业的小区
                    List<String> residenceCommunityIds = new ArrayList<>();
                    if (enterpriseTagIds.contains(4L)) {
                        List<Community> communities = communityRepository.findByOrgIdAndStatus(enterpriseId, 1);
                        residenceCommunityIds = communities.stream().map(Community::getId).distinct().collect(Collectors.toList());// 小区id
                    }

                    where.append(" and ( h." + areaTag + " = ? or s.org_id = ? or s.match_user_id = ? or s.community_id in ");
                    args.add(areaId);
                    args.add(hierarchyOrgId);
                    args.add(userId);
                    if (!residenceCommunityIds.isEmpty()) {
                        where.append(SqlUtils.foreachIn(residenceCommunityIds.size()) + ")");
                        args.addAll(residenceCommunityIds);
                    } else {
                        where.append("(?) )");
                        args.add(null);
                    }
                } else {
                    where.append(" and s.match_user_id = ?");
                    args.add(userId);
                }
            }

            if (StringUtils.isNotBlank(matchUserName)) {
                where.append(" AND l.`match_user_name` LIKE ?");
                args.add("%" + matchUserName + "%");
            }
            if (StringUtils.isNotBlank(communityId)) {
                where.append(" AND s.`community_id` = ?");
                args.add(communityId);
            }
            if (buildId != null) {
                where.append(" AND s.`build_id` = ?");
                args.add(buildId);
            }
            if (unitId != null) {
                where.append(" AND s.`unit_id` = ?");
                args.add(unitId);
            }
            if (StringUtils.isNotBlank(roomNumber)) {
                where.append(" AND s.`room_number` = ?");
                args.add(roomNumber);
            }
            if (type != null) {
                where.append(" and l.type = ?");
                args.add(type);
            }
            if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
                where.append(" and l.operation_time >= ? AND l.operation_time < ?");
                args.add(beginDate);
                args.add(DateUtils.getAddDaysTime(endDate, DateUtils.FORMAT_DATE_8, 1));
            }
            // 总记录数
            Long total = jdbcTemplate.queryForObject(
                    "SELECT count(1) FROM `saas_house_lock_frozen` l LEFT JOIN saas_smart_lock s ON l.lock_id = s.id left join saas_house h on l.house_id = h.id"
                            + where,
                    args.toArray(), Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<LockFrozenVO> list = jdbcTemplate
                    .query("select l.type,l.match_user_name as matchUserName,s.community_name as communityName,s.build_name as buildName,\n"
                            + "s.unit_name as unitName,s.room_number as roomNumber,l.operation_time as operationTime,l.operation_time as alarmTime,l.reason,s.operator_id,s.operator_org_id\n"
                            + "from `saas_house_lock_frozen` l LEFT JOIN saas_smart_lock s ON l.lock_id = s.id left join saas_house h on l.house_id = h.id" + where
                            + FROZEN_ORDER + SQL_PAGE, new BeanPropertyRowMapper<>(LockFrozenVO.class), args.toArray());
            // 新增冻结机构名称和操作人信息
            for (LockFrozenVO vo : list) {
                vo.setOperationTime(DateUtils.format(vo.getOperationTime(), DateUtils.FORMAT_DATETIME_14,
                        DateUtils.FORMAT_DATETIME_14));
                String operatorId = vo.getOperatorId();
                Long operatorOrgId = vo.getOperatorOrgId();
                Optional<Department> departmentS = departmentRepository.findById(operatorOrgId);
                if (departmentS != null) {
                    Department department = departmentS.get();
                    String orgName = department.getName();
                    vo.setOrgName(orgName);
                }
                // 查询出操作人信息
                User byId = userRepository.findById(operatorId);
                if (byId != null) {
                    String name = byId.getName();
                    String mobile = byId.getMobile();
                    //   嗨小克小程序==》将操作人员的字段数据从组织机构名字封装到操作人员账号的名字
                    vo.setOperatorName(name);
                    vo.setOperatorMobile(mobile);
                }
                //    新增操作人名称 xiaolong 20230316
                //   嗨小克小程序==》将操作人员的字段数据从组织机构名字封装到操作人员账号的名字
                /*Optional<Department> byId1 = departmentRepository.findById(operatorOrgId);
                if (byId1.isPresent()) {
                    String name = byId1.get().getName();
                    vo.setOperatorName(name);
                }*/
            }
            apiData.setData(list);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockAppService frozenOrUnfrozenLog Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    /**
     * 查看授权密码
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  授权用户id
     * @return
     */
    public ResultBean<AuthPwdVO> findAuthPwd(String accessToken, Long lockAuthId) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }

            Date date = new Date();
            // SmartLockPwd smartLockPwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
            // String sql = "SELECT * FROM saas_smart_lock_pwd WHERE lock_auth_id = ? and type != 3 ";
            // SmartLockPwd smartLockPwd = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(SmartLockPwd.class),lockAuthId);
            // String sql = "SELECT * FROM saas_smart_lock_pwd WHERE lock_auth_id = ? and (type = 1 or type = 2)";
            // SmartLockPwd smartLockPwd = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(SmartLockPwd.class),lockAuthId);
            SmartLockPwd smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 1);
            if (smartLockPwd == null) {
                smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 2);
            }
            AuthPwdVO authPwdVO = new AuthPwdVO();

            if (smartLockPwd == null) {
                return ResultBean.successfulResult(null);
            } else {
                authPwdVO.setLockAuthId(lockAuthId);
                Integer type = smartLockPwd.getType();
                authPwdVO.setType(type);

                authPwdVO.setAuthType(smartLockPwd.getAuthType());
                if (type == 1) {
                    authPwdVO.setPassword(smartLockPwd.getPassword());
                }

                Date endTime = smartLockPwd.getEndTime();
                if (date.compareTo(endTime) == -1) {
                    int days = DateUtils.daysBetween(date, endTime);
                    if (days == 0) {
                        authPwdVO.setDays(1);
                    } else {
                        authPwdVO.setDays(days);
                    }
                } else {
                    authPwdVO.setDays(0);
                }

                authPwdVO.setTimes(smartLockPwd.getTimes());
            }

            return ResultBean.successfulResult(authPwdVO);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 查看授权卡
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  授权用户id
     * @param type        卡类型：1身份证 2CPU卡
     * @return
     */
    public ResultBean<AuthCardVO> findAuthCard(String accessToken, Long lockAuthId, Integer type) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("卡类型不存在");
            }

            Date date = new Date();
            SmartLockCard smartLockCard = smartLockCardRepository.findByLockAuthIdAndType(lockAuthId, type);
            AuthCardVO authCardVO = new AuthCardVO();

            if (smartLockCard == null) {
                return ResultBean.successfulResult(null);
            } else {
                authCardVO.setLockAuthId(lockAuthId);
                authCardVO.setAuthType(smartLockCard.getAuthType());

                Date endTime = smartLockCard.getEndTime();
                if (date.compareTo(endTime) == -1) {
                    int days = DateUtils.daysBetween(date, endTime);
                    authCardVO.setDays(days);
                } else {
                    authCardVO.setDays(0);
                }
            }
            return ResultBean.successfulResult(authCardVO);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 读取临时密码月次数和使用次数
     *
     * @param accessToken 权限鉴定
     * @param lockId      锁id
     * @return
     */
    public ResultBean<Object> getTempPwd(String accessToken, Long lockId) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }

            Optional<SmartLock> smartLock = smartLockRepository.findById(lockId);
            if (smartLock.isPresent()) {
                // MatchUserLockAuthor byIdAndHouseId = matchUserLockAuthorRepository.findByHouseId(smartLock.get().getHouseId());
                /*List<MatchUserLockAuthor> byIdAndHouseIdList = matchUserLockAuthorRepository.findByHouseId(smartLock.get().getHouseId());
                if (!byIdAndHouseIdList.isEmpty()) {
                    byIdAndHouseIdList.get(0).setUseNumber(byIdAndHouseIdList.get(0).getUseNumber());// 使用次数
                    return ResultBean.successfulResult(byIdAndHouseIdList.get(0));
                }*/
                // String pwdNum = redisTemplate.opsForValue().get("repeatPwd:" + smartLock.get().getId());
                // Integer usrPwd ;
                // if (StrUtil.isEmpty(pwdNum)) {
                //     usrPwd = 0;
                // }else {
                //     usrPwd = Integer.valueOf(pwdNum);
                // }


                // 都未找到时，返回默认值
                MatchUserLockAuthorVO matchUserLockAuthorVO = new MatchUserLockAuthorVO();
                matchUserLockAuthorVO.setAuthorNumber(5);
                matchUserLockAuthorVO.setPasswordValidity(1);

                if (smartLock.get().getBrandId() == 5) {
                    List<Date> latelyTenMinsTimeslot = this.getLatelyTenMinsTimeslot();
                    matchUserLockAuthorVO.setStartValidTime(latelyTenMinsTimeslot.get(0));
                    matchUserLockAuthorVO.setEndValidTime(latelyTenMinsTimeslot.get(1));
                }

                List<MatchUserLockAuthor> matchUserLockAuthors = matchUserLockAuthorRepository.findByHouseId(smartLock.get().getHouseId());
                if (CollectionUtil.isNotEmpty(matchUserLockAuthors)) {
                    if (smartLock.get().getBrandId() == 5) {
                        matchUserLockAuthorVO.setAuthorNumber(matchUserLockAuthors.get(0).getAuthorNumber());
                    }
                    matchUserLockAuthorVO.setUseNumber(matchUserLockAuthors.get(0).getUseNumber());
                } else {
                    matchUserLockAuthorVO.setUseNumber(0);
                }
                return ResultBean.successfulResult(matchUserLockAuthorVO);
            }
            return ResultBean.failedResultWithMsg("智能锁不存在");
        } catch (Exception e) {
            log.error("LockAppService getTempPwd Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 授权临时密码
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  授权用户id
     * @param lockId      智能锁id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Object> authTemporaryPwd(String accessToken, Long lockAuthId, Long lockId) throws CustomException {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            String userId = token.getId();
            AppUser user = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
            if (user == null) {
                return ResultBean.failedResultOfParamWithMsg("用户信息不存在");
            }

            String mobile = user.getPhone();

            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }

            // 验证是不是承租人
            // 验证是否有剩余授权次数
            // 企业用户不扣减次数
            // 1、不在承租人库的用户，操作智能锁授权，不受次数限制(如机构用户)
            // 2、在承租人库的用户，操作智能锁授权，默认月度5次，如果有设置，按设置次数限制
            // 3、月度授权次数，每月1号凌晨重置（按照设置的次数为依据重置）
            // 4、设置次数后马上生效

            Optional<SmartLock> byId = smartLockRepository.findById(lockId);
            SmartLock smartLock = byId.get();
            if (!byId.isPresent()) {
                return ResultBean.failedResultOfParamWithMsg("锁安装信息未找到");
            }

            // 锁冻结不给申请
            if (smartLock.getMechineStatus().equals(2)) {
                return ResultBean.failedResultOfParamWithMsg("智能锁已被冻结");
            }

            // 获取短信发送次数
            String redis = redisTemplate.opsForValue().get("repeatPwd:" + mobile);
            if (StringUtils.isNotBlank(redis)) {
                int num = Integer.parseInt(redis);
                if (num > 4) {
                    return ResultBean.failedResultWithMsg("已超过今日申请上限，请明天再试");
                }
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();
            // 2023-3-28 zhiping [bug #372] 用同住人的小程序申请临时密码，承租人收到短信，申请人没收到短信
            // mobile = smartLockAuth.getMobile();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }
            House house = houseOptional.get();

            // 如临时密码未失效则使用原有临时密码 不扣减次数
            String pwd = redisService.getAuthTemporaryPwd(mobile, smartLockAuth.getHouseId());
            if (StringUtils.isNotBlank(pwd)) {
                // 发送短信
                String str = smsService.sendTemplateMsgSms(mobile, pwd);
                if (str.equals("success")) {
                    // 如果是承租人授权，更新公租房锁授权状态
                    if (house.getHouseNature() == 1) {
                        if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                            String houseId = smartLockAuth.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 1);
                        }
                    }

                    // 短信发送次数+1
                    String plus = "";
                    if (StringUtils.isNotBlank(redis)) {
                        int num = Integer.parseInt(redis);
                        plus = String.valueOf(num + 1);
                    } else {
                        plus = "1";
                    }
                    redisTemplate.opsForValue().set("repeatPwd:" + mobile, plus, DateUtils.getTimeMillis(), TimeUnit.SECONDS);

                    return ResultBean.successfulResultWithMsg("指令下发成功", null);
                } else {
                    return ResultBean.failedResultWithMsg("指令下发成功，短信通知失败");
                }
            }

            // 根据房屋ID查到承租人房屋授权次数设置数据(因为一个房屋只有一把锁)
            // MatchUserLockAuthor matchUserLockAuthor1 = matchUserLockAuthorRepository.findByHouseId(smartLock.getHouseId());
            log.info("临时密码授权, mobile={}", mobile);
            // 查询承租人/同住人，都扣减次数
            String sqlUser = "SELECT * FROM saas_community_house_user hu WHERE hu.type in (1, 2, 3) AND hu.status = 1 AND hu.mobile = ? ";
            List<MatchUserLockAuthor> listUser = jdbcTemplate.query(sqlUser, new BeanPropertyRowMapper<>(MatchUserLockAuthor.class), mobile);

            Integer authorNumber = 5;
            Integer useNumber = 0;
            Integer passwordValidity = 1;
            if (!listUser.isEmpty()) {
                // 查询房屋临时密码次数
                String sql = "SELECT mau.* FROM m_match_user_lock_author mau WHERE mau.house_id = ?";
                List<MatchUserLockAuthor> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MatchUserLockAuthor.class), smartLock.getHouseId());
                MatchUserLockAuthor entity = null;
                // 有设置记录
                if (!list.isEmpty()) {
                    entity = list.get(0);
                    // 申请使用次数
                    authorNumber = entity.getAuthorNumber();
                    // 有效期天数
                    passwordValidity = entity.getPasswordValidity();
                    // 使用次数
                    useNumber = entity.getUseNumber();
                } else {
                    entity = new MatchUserLockAuthor();
                    // 默认5次
                    entity.setAuthorNumber(authorNumber);
                    // 查询承租人库数据
                    List<MatchUserHouse> hList = matchUserHouseRepository.findByHouseId(smartLock.getHouseId());
                    if (!hList.isEmpty()) {
                        entity.setMatchUserStockId(hList.get(0).getMatchUserStockId());
                    } else {
                        log.error("临时密码授权, 房屋承租人库数据未找到, houseId={}", smartLock.getHouseId());
                    }
                    entity.setOperatorUserId(1l);
                    entity.setUseNumber(useNumber);
                    entity.setPasswordValidity(passwordValidity);
                    entity.setCreateTime(new Date());
                    String date = DateUtils.format(new Date(), DateUtils.FORMAT_6);
                    entity.setEffectiveJulyDate(date);
                    entity.setLastUpdateTime(new Date());
                    entity.setHouseId(smartLock.getHouseId());
                    matchUserLockAuthorRepository.save(entity);
                }

                // 承租人，判断剩余可用次数
                if (authorNumber - useNumber > 0) {
                    ResultBean<Object> objectResultBean = authPwd(accessToken, lockAuthId, lockId, 2, null, 2, passwordValidity);
                    if (objectResultBean != null && objectResultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                        entity.setUseNumber(entity.getUseNumber() + 1);
                        entity.setLastUpdateTime(new Date());
                        matchUserLockAuthorRepository.save(entity);
                        return ResultBean.successfulResult(entity);
                    } else {
                        // 授权失败
                        return objectResultBean;
//                        throw new CustomException("授权失败");
                    }
                } else {
                    return ResultBean.failedResultOfParamWithMsg("授权次数已达上限");
                }
            }
            log.info("临时密码授权, 机构用户授权, mobile={}", mobile);
            // 机构用户，不用验证次数，不扣减次数
            return authPwd(accessToken, lockAuthId, lockId, 2, null, 2, passwordValidity);
        } catch (Exception e) {
            log.error("LockAppService authTempPwd Exception = {}" + e.getMessage(), e);
            throw new CustomException("临时密码授权异常");
//            throw new CustomException("该用户已经授权密码");
        }
    }

    /**
     * 授权临时密码
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Object> authTemporaryPassword(String accessToken, String houseId1) throws CustomException {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            String mobile = token.getPhone();

            SmartLockAuth byHouseIdAndMobile = smartLockAuthRepository.findByHouseIdAndMobile(houseId1, mobile);
            if (byHouseIdAndMobile == null) {
                throw new RuntimeException("智能锁授权未找到");
            }
            Long lockAuthId = byHouseIdAndMobile.getId();
            Long lockId = byHouseIdAndMobile.getLockId();
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }

            // 验证是不是承租人
            // 验证是否有剩余授权次数
            // 企业用户不扣减次数
            // 1、不在承租人库的用户，操作智能锁授权，不受次数限制(如机构用户)
            // 2、在承租人库的用户，操作智能锁授权，默认月度5次，如果有设置，按设置次数限制
            // 3、月度授权次数，每月1号凌晨重置（按照设置的次数为依据重置）
            // 4、设置次数后马上生效

            Optional<SmartLock> byId = smartLockRepository.findById(lockId);
            SmartLock smartLock = byId.get();
            if (!byId.isPresent()) {
                return ResultBean.failedResultOfParamWithMsg("锁安装信息未找到");
            }

            // 获取短信发送次数
            String redis = redisTemplate.opsForValue().get("repeatPwd:" + mobile);
            // if (StringUtils.isNotBlank(redis)) {
            //    int num = Integer.parseInt(redis);
            //    if (num >= 4) {
            //        return ResultBean.failedResultWithMsg("已超过今日申请上限，请明天再试");
            //    }
            //}

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();
            // 2023-3-28 zhiping [bug #372] 用同住人的小程序申请临时密码，承租人收到短信，申请人没收到短信
            // mobile = smartLockAuth.getMobile();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }
            House house = houseOptional.get();

            // 如临时密码未失效则使用原有临时密码 不扣减次数
            String pwd = redisService.getAuthTemporaryPwd(mobile, smartLockAuth.getHouseId());
            if (StringUtils.isNotBlank(pwd)) {
                // 发送短信
                String str = smsService.sendTemplateMsgSms(mobile, pwd);
                if (str.equals("success")) {
                    // 如果是承租人授权，更新公租房锁授权状态
                    if (house.getHouseNature() == 1) {
                        if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                            String houseId = smartLockAuth.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 1);
                        }
                    }

                    // 短信发送次数+1
                    String plus = "";
                    if (StringUtils.isNotBlank(redis)) {
                        int num = Integer.parseInt(redis);
                        plus = String.valueOf(num + 1);
                    } else {
                        plus = "1";
                    }
                    redisTemplate.opsForValue().set("repeatPwd:" + mobile, plus, DateUtils.getTimeMillis(), TimeUnit.SECONDS);

                    return ResultBean.successfulResultWithMsg("指令下发成功", null);
                } else {
                    return ResultBean.failedResultWithMsg("指令下发成功，短信通知失败");
                }
            }

            // 根据房屋ID查到承租人房屋授权次数设置数据(因为一个房屋只有一把锁)
            // MatchUserLockAuthor matchUserLockAuthor1 = matchUserLockAuthorRepository.findByHouseId(smartLock.getHouseId());
            log.info("临时密码授权, mobile={}", mobile);
            // 查询承租人/同住人，都扣减次数
            String sqlUser = "SELECT * FROM saas_community_house_user hu WHERE hu.type in (1, 2) AND hu.status = 1 AND hu.mobile = ? ";
            List<MatchUserLockAuthor> listUser = jdbcTemplate.query(sqlUser, new BeanPropertyRowMapper<>(MatchUserLockAuthor.class), mobile);

            Integer authorNumber = 5;
            Integer useNumber = 0;
            Integer passwordValidity = 1;
            if (!listUser.isEmpty()) {
                // 查询房屋临时密码次数
                String sql = "SELECT mau.* FROM m_match_user_lock_author mau WHERE mau.house_id = ?";
                List<MatchUserLockAuthor> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MatchUserLockAuthor.class), smartLock.getHouseId());
                MatchUserLockAuthor entity = null;
                // 有设置记录
                if (!list.isEmpty()) {
                    entity = list.get(0);
                    // 申请使用次数
                    authorNumber = entity.getAuthorNumber();
                    // 有效期天数
                    passwordValidity = entity.getPasswordValidity();
                    // 使用次数
                    useNumber = entity.getUseNumber();
                } else {
                    entity = new MatchUserLockAuthor();
                    // 默认5次
                    entity.setAuthorNumber(authorNumber);
                    // 查询承租人库数据
                    List<MatchUserHouse> hList = matchUserHouseRepository.findByHouseId(smartLock.getHouseId());
                    if (!hList.isEmpty()) {
                        entity.setMatchUserStockId(hList.get(0).getMatchUserStockId());
                    } else {
                        log.error("临时密码授权, 房屋承租人库数据未找到, houseId={}", smartLock.getHouseId());
                    }
                    entity.setOperatorUserId(1l);
                    entity.setUseNumber(useNumber);
                    entity.setPasswordValidity(passwordValidity);
                    entity.setCreateTime(new Date());
                    String date = DateUtils.format(new Date(), DateUtils.FORMAT_6);
                    entity.setEffectiveJulyDate(date);
                    entity.setLastUpdateTime(new Date());
                    entity.setHouseId(smartLock.getHouseId());
                    matchUserLockAuthorRepository.save(entity);
                }

                // 承租人，判断剩余可用次数
                if (authorNumber - useNumber > 0) {
                    ResultBean<Object> objectResultBean = authPwd(accessToken, lockAuthId, lockId, 2, null, 2, passwordValidity);
                    if (objectResultBean != null && objectResultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                        entity.setUseNumber(entity.getUseNumber() + 1);
                        entity.setLastUpdateTime(new Date());
                        matchUserLockAuthorRepository.save(entity);
                        return ResultBean.successfulResult(entity);
                    } else {
                        // 授权失败
                        // return objectResultBean;
                        throw new CustomException("授权失败");
                    }
                } else {
                    return ResultBean.failedResultOfParamWithMsg("授权次数已达上限");
                }
            }
            log.info("临时密码授权, 机构用户授权, mobile={}", mobile);
            // 机构用户，不用验证次数，不扣减次数
            return authPwd(accessToken, lockAuthId, lockId, 2, null, 2, passwordValidity);
        } catch (Exception e) {
            log.error("LockAppService authTempPwd Exception = {}" + e.getMessage(), e);
            throw new CustomException("临时密码授权异常");
        }
    }


    /**
     * 公寓用户入住时授权开门权限
     *
     * @param type 0正常申请 1不扣减密码次数
     * @return
     */
    public ResultBean<Object> authOpenDoor(String accessToken, String houseId, Integer minute, Integer type) throws BizException {

        List<SmartLock> smartLocks = smartLockRepository.findByHouseId(houseId);
        if (CollectionUtil.isEmpty(smartLocks)) {
            return ResultBean.failedResult("没有智能锁信息");
        }
        if (smartLocks.get(0).getBrandId() == 6 || smartLocks.get(0).getBrandId() == 5) {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            String id = token.getId();
            String phone = token.getPhone();
            Optional<AppUser> appUser = appUserRepository.findById(id);
            String facePic = ossBucketUrl + appUser.get().getFacePic();


            SmartLockAuth byHouseIdAndMobile = smartLockAuthRepository.findByHouseIdAndMobile(houseId, phone);
            if (byHouseIdAndMobile == null) {
                throw new RuntimeException("智能锁授权未找到");
            }
            Long lockAuthId = byHouseIdAndMobile.getId();
            Long lockId = byHouseIdAndMobile.getLockId();
            String sn = smartLocks.get(0).getSn();
            SmartLockFace smartLockFace = new SmartLockFace();
            smartLockFace.setSn(sn);
            smartLockFace.setFaceImage(facePic);
            smartLockFace.setAuthType(SmartLockFace.PERMANENT_FLAG_YES);
            smartLockFace.setLockId(lockId);
            smartLockFace.setLockAuthId(lockAuthId);
            ResultBean<String> stringResultBean = smartLockBrandService.operationFace(smartLockFace, smartLocks.get(0).getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();
            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authPwd---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            }

            // smartLockFace.setReturnFaceId(Long.valueOf(resultData));
            if (smartLocks.get(0).getBrandId() == 8L) {
                String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                smartLockFace.setIdentification(phoneNo);
                String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                smartLockFace.setKeyId(keyId);
            } else {
                smartLockFace.setIdentification(resultData);
                smartLockFace.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
            }
            smartLockFace.setStatus(1);
            smartLockFace.setCreateTime(new Date());
            smartLockFaceRepository.save(smartLockFace);
            SmartLock smartLock = smartLocks.get(0);

            // bug 2397
            Integer oauthNumber = smartLock.getOauthNumber();
            smartLock.setOauthNumber(oauthNumber + 1);
            smartLock.setMechineStatus(1);
            smartLockRepository.save(smartLock);
            this.updateOauthNumber(smartLock.getBrandId(), smartLock.getId());
            byHouseIdAndMobile.setFaceStatus(1);
            smartLockAuthRepository.save(byHouseIdAndMobile);
            return ResultBean.successfulResultWithMsg("授权人脸成功", StatusCode.SUCCESS_CODE_10000);
        } else {
            return authTimePassword(accessToken, houseId, minute, type, null);
        }
    }

    /**
     * 授权时效密码
     *
     * @param type    0正常申请 1不扣减密码次数
     * @param orderId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Object> authTimePassword(String accessToken, String houseId1, Integer minute, Integer type, String orderId) throws BizException {

        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null)
            return ResultBean.failedResultOfToken();

        String mobile = token.getPhone();

        SmartLockAuth byHouseIdAndMobile = smartLockAuthRepository.findByHouseIdAndMobile(houseId1, mobile);
        if (byHouseIdAndMobile == null) {
            throw new RuntimeException("智能锁授权未找到");
        }
        Long lockAuthId = byHouseIdAndMobile.getId();
        Long lockId = byHouseIdAndMobile.getLockId();
        if (lockAuthId == null) {
            return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
        }

        if (lockId == null) {
            return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
        }

        /**
         * 验证智能锁，或者 密码， 指纹 身份证 CPU卡  蓝牙 是否冻结
         * true  代表未冻结
         * false  代表已冻结
         * @param lockId 智能锁id
         * @param lockAuthId 用户授权id
         */
        Boolean FreezeBoolean = lockCurrencyService.freezeOrNot(lockId, lockAuthId);
        if (!FreezeBoolean) {
            return ResultBean.failedResultWithMsg("授权失败，智能锁已冻结或授权已冻结！");
        }

        // 验证是不是承租人
        // 验证是否有剩余授权次数
        // 企业用户不扣减次数
        // 1、不在承租人库的用户，操作智能锁授权，不受次数限制(如机构用户)
        // 2、在承租人库的用户，操作智能锁授权，默认月度5次，如果有设置，按设置次数限制
        // 3、月度授权次数，每月1号凌晨重置（按照设置的次数为依据重置）
        // 4、设置次数后马上生效

        Optional<SmartLock> byId = smartLockRepository.findById(lockId);
        if (!byId.isPresent()) {
            return ResultBean.failedResultOfParamWithMsg("锁安装信息未找到");
        }
        SmartLock smartLock = byId.get();

        // 获取短信发送次数
        String redis = redisTemplate.opsForValue().get("repeatPwd:" + mobile);

        Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
        if (!authOpt.isPresent()) {
            return ResultBean.failedResultWithMsg("用户授权明细不存在");
        }
        SmartLockAuth smartLockAuth = authOpt.get();

        Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
        if (!houseOptional.isPresent()) {
            return ResultBean.failedResultWithMsg("房屋不存在");
        }
        House house = houseOptional.get();

        // 如临时密码未失效则使用原有临时密码 不扣减次数
        String pwd = redisService.getAuthTemporaryPwd(mobile, smartLockAuth.getHouseId());
        if (StringUtils.isNotBlank(pwd)) {
            // 发送短信
            String str = smsService.sendTemplateMsgSms(mobile, pwd);
            if ("success".equals(str)) {
                // 如果是承租人授权，更新公租房锁授权状态
                if (house.getHouseNature() == 1) {
                    if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                        String houseId = smartLockAuth.getHouseId();
                        houseRepository.updateLockStatusById(houseId, 1);
                    }
                }
                // 前面type写死了，根据pwd是否为空判断既可
                // if (type == 0) {
                //     // 短信发送次数+1
                //     String plus = "";
                //     if (StringUtils.isNotBlank(redis)) {
                //         int num = Integer.parseInt(redis);
                //         plus = String.valueOf(num + 1);
                //     } else {
                //         plus = "1";
                //     }
                // }
                redisTemplate.opsForValue().set("repeatPwd:" + mobile, redis, DateUtils.getTimeMillis(), TimeUnit.SECONDS);

                this.insertOrderPwdNum(orderId, token);
                return ResultBean.successfulResultWithMsg("授权密码成功", null);
            } else {
                return ResultBean.failedResultWithMsg("授权密码成功，短信通知失败");
            }
        }

        // 根据房屋ID查到承租人房屋授权次数设置数据(因为一个房屋只有一把锁)
        // MatchUserLockAuthor matchUserLockAuthor1 = matchUserLockAuthorRepository.findByHouseId(smartLock.getHouseId());
        log.info("临时密码授权, mobile={}", mobile);
        // 查询承租人/同住人，都扣减次数
        String sqlUser = "SELECT * FROM saas_community_house_user hu WHERE hu.type in (1, 2) AND hu.status = 1 AND hu.mobile = ? ";
        List<MatchUserLockAuthor> listUser = jdbcTemplate.query(sqlUser, new BeanPropertyRowMapper<>(MatchUserLockAuthor.class), mobile);

        Integer authorNumber = 5;
        Integer useNumber = 0;
        Integer passwordValidity = 1;
        if (!listUser.isEmpty()) {

            // 查询房屋临时密码次数
            String sql = "SELECT mau.* FROM m_match_user_lock_author mau WHERE mau.house_id = ?";
            List<MatchUserLockAuthor> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MatchUserLockAuthor.class), smartLock.getHouseId());
            MatchUserLockAuthor entity = null;
            // 有设置记录
            if (!list.isEmpty()) {
                entity = list.get(0);
                // 申请使用次数
                authorNumber = entity.getAuthorNumber();
                // 有效期天数
                passwordValidity = entity.getPasswordValidity();
                // 使用次数
                useNumber = entity.getUseNumber();
            } else {
                entity = new MatchUserLockAuthor();
                // 默认5次
                entity.setAuthorNumber(authorNumber);
                // 查询承租人库数据
                List<MatchUserHouse> hList = matchUserHouseRepository.findByHouseId(smartLock.getHouseId());
                if (!hList.isEmpty()) {
                    entity.setMatchUserStockId(hList.get(0).getMatchUserStockId());
                } else {
                    log.error("临时密码授权, 房屋承租人库数据未找到, houseId={}", smartLock.getHouseId());
                }
                entity.setOperatorUserId(1l);
                entity.setUseNumber(useNumber);
                entity.setPasswordValidity(passwordValidity);
                entity.setCreateTime(new Date());
                String date = DateUtils.format(new Date(), DateUtils.FORMAT_6);
                entity.setEffectiveJulyDate(date);
                entity.setLastUpdateTime(new Date());
                entity.setHouseId(smartLock.getHouseId());
                matchUserLockAuthorRepository.save(entity);
            }

            // 承租人，判断剩余可用次数
            ResultBean<Object> objectResultBean = authTimePwd(accessToken, lockAuthId, lockId, 2, null, 2, passwordValidity, minute, type);
            if (objectResultBean != null && objectResultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                if (type == 0) {
                    entity.setUseNumber(entity.getUseNumber() + 1);
                }
                entity.setLastUpdateTime(new Date());
                matchUserLockAuthorRepository.save(entity);

                this.insertOrderPwdNum(orderId, token);

                return ResultBean.successfulResultWithMsg("授权密码成功", null);
            } else {
                // 授权失败
                // return objectResultBean;
                throw new BizException("授权失败");
            }
            /*if (authorNumber - useNumber > 0) {
            } else {
                return ResultBean.failedResultOfParamWithMsg("授权次数已达上限");
            }*/
        }
        return ResultBean.failedResultWithMsg("授权失败");
    }

    public void insertOrderPwdNum(String orderId, TokenRedisVo token) {
        if (StrUtil.isNotEmpty(orderId)) {
            // 公寓订单临时密码申请次数
            Order order = iOrderService.selectOrderById(orderId);
            HousingAllocation housingAllocation = GsonUtil.toBean(order.getAllocationContent(), HousingAllocation.class);
            DateTime nowTime = DateUtil.date();
            OrderPasswordRecord passwordRecord = new OrderPasswordRecord();
            passwordRecord.setOrderId(orderId);
            passwordRecord.setCreateTime(nowTime);
            passwordRecord.setCreateBy(token.getId());
            if (HousingAllocation.APARTMENT_TYPE_SHORT.equals(housingAllocation.getApartmentType())) {
                passwordRecord.setValidityStartTime(order.getCheckInTime());
                passwordRecord.setValidityEndTime(order.getCheckOutTime());
            } else if (HousingAllocation.APARTMENT_TYPE_LONG.equals(housingAllocation.getApartmentType())) {
                if (DateUtil.month(order.getCheckInTime()) == nowTime.month()) {
                    passwordRecord.setValidityStartTime(order.getCheckInTime());
                    passwordRecord.setValidityEndTime(DateUtil.endOfMonth(nowTime));
                } else if (nowTime.dayOfMonth() == 1) {
                    if (DateUtil.month(order.getCheckOutTime()) == nowTime.month()) {
                        passwordRecord.setValidityStartTime(DateUtil.beginOfMonth(nowTime));
                        passwordRecord.setValidityEndTime(order.getCheckOutTime());
                    } else {
                        passwordRecord.setValidityStartTime(DateUtil.beginOfMonth(nowTime));
                        passwordRecord.setValidityEndTime(DateUtil.endOfMonth(nowTime));
                    }
                }
            }
            iOrderPasswordRecordService.insertOrderPasswordRecord(passwordRecord);
        }
    }

    /**
     * 授权密码
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  授权用户id
     * @param lockId      智能锁id
     * @param type        密码类型：1自定义密码 2 授权密码
     * @param password    自定义密码
     * @param authType    设置方式：1永久 2时间期限 3次数
     * @param value       输入值
     * @return
     */
    @Transactional
    public ResultBean<Object> authTimePwd(String accessToken, Long lockAuthId, Long lockId, Integer type, String password,
                                          Integer authType, Integer value, Integer minute, Integer passwordType) {
        log.info(
                "LockAppService authPwd, accessToken={}, lockAuthId={}, lockId={}, type{}, password={}, authType={}, value={}",
                accessToken, lockAuthId, lockId, type, password, authType, value);
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("密码类型不存在");
            }
            if (authType == null) {
                return ResultBean.failedResultOfParamWithMsg("授权方式不存在");
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();
            String mobile = smartLockAuth.getMobile();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }
            House house = houseOptional.get();

            // 获取短信发送次数
            String redis = redisTemplate.opsForValue().get("repeatPwd:" + mobile);
            // 授权前更新未激活智能锁sn值
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }

            SmartLock smartLock = lockOptional.get();
            String mac = smartLock.getMac();
            String sn = smartLock.getSn();
            if (StringUtils.isBlank(sn)) {
                ResultBean<String> resultBean = smartLockBrandService.getSnByMac(mac, smartLock.getHouseId(),
                        smartLock.getBrandId());
                if (resultBean == null) {
                    return ResultBean.failedResultOfParamWithMsg("智能锁ID为空, 已重新注册, 稍后重试");
                }
                String resultSn = resultBean.getResultData();
                if (StringUtils.isBlank(resultSn)) {
                    return ResultBean.failedResultWithMsg("设备状态异常");
                } else {
                    smartLock.setSn(resultSn);
                    smartLock.setMechineStatus(1);
                    smartLockRepository.save(smartLock);
                }
            }


            SmartLockPwd smartLockPwd = null;
            if (smartLock.getBrandId() != 5L) {
                if (type == 3) {
                    smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, type);
                } else {
                    smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 1);
                    if (smartLockPwd == null) {
                        smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 2);
                    }
                }
            }
            if (smartLockPwd == null) {// 新增
                smartLockPwd = new SmartLockPwd();
                smartLockPwd.setLockAuthId(lockAuthId);
                smartLockPwd.setLockId(lockId);
                smartLockPwd.setCreateTime(new Date());
                smartLockPwd.setLastUpdateTime(smartLockPwd.getCreateTime());

                // 密码序号
                List<SmartLockPwd> smartLockPwds = smartLockPwdRepository.findByLockId(lockId);
                if (smartLockPwds != null && !smartLockPwds.isEmpty()) {// 已存在序号
                    List<Integer> indexs = smartLockPwds.stream().filter(vo -> vo.getPwdIndex() != null)
                            .map(SmartLockPwd::getPwdIndex).distinct().collect(Collectors.toList());
                    Integer max = Collections.max(indexs);
                    if (max == 49) {
                        // 排除已有序号，取1-49间的最小值
                        List<Integer> list = new ArrayList<>();
                        for (int i = 0, j = 49; i < j; ++i) {
                            list.add(i + 1);
                        }
                        for (Integer i : indexs) {
                            list.remove(i);
                        }
                        Integer min = Collections.min(list);
                        smartLockPwd.setPwdIndex(min);
                    } else {
                        smartLockPwd.setPwdIndex(max + 1);// 取智能锁密码序号最大值 +1
                    }
                } else {// 没有序号
                    smartLockPwd.setPwdIndex(1);
                }
            } else {// 修改
                smartLockPwd.setLastUpdateTime(new Date());
            }
            // 新增天网互联密码标识
            String identification = smartLockPwd.getIdentification();
            if (StrUtil.isEmpty(identification)) {
                identification = "L" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
            }
            smartLockPwd.setIdentification(identification);
            smartLockPwd.setType(type);
            smartLockPwd.setAuthType(authType);
            smartLockPwd.setAuthTime(new Date());
            smartLockPwd.setStatus(0);// 0待执行
            if (smartLock.getBrandId() == 3L) {
                smartLockPwd.setStatus(1);
            }

            if (type == 1) {
                smartLockPwd.setPassword(password);
            } else if (type == 2) {
                smartLockPwd.setPassword(RandomNoUtils.getRandomNum(6));
            } else if (type == 3) {
                smartLockPwd.setPassword(RandomNoUtils.getRandomNum(6));
            }

            Date date = new Date();

            // 密码有效期
            smartLockPwd.setStartTime(date);
            Date addDaysTime = DateUtil.offsetMinute(new Date(), minute);
            smartLockPwd.setEndTime(addDaysTime);
            smartLockPwd.setLimitDay(value);


            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            // 新增天网互联密码标识
            smartLockVO.setIdentification(smartLockPwd.getIdentification());
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setStartTime(DateUtils.format(smartLockPwd.getStartTime(), DateUtils.FORMAT_14));
            smartLockVO.setEndTime(DateUtils.format(smartLockPwd.getEndTime(), DateUtils.FORMAT_14));
            if (smartLock.getBrandId() == 3L) {// 亚略特
                smartLockVO.setStartTime(DateUtils.format(smartLockPwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                smartLockVO.setEndTime(DateUtils.format(smartLockPwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
            }
            smartLockVO.setPassword(smartLockPwd.getPassword());
            if (authType == 1 || authType == 2) {
                smartLockVO.setAuthType("2");
            } else if (authType == 3) {
                smartLockVO.setAuthType("5");
                smartLockVO.setTimes(smartLockPwd.getTimes());
            }
            smartLockVO.setIndex(smartLockPwd.getPwdIndex());
            smartLockVO.setDevMac(smartLock.getMac());
            smartLockVO.setAuthInfoId(lockAuthId);
            smartLockVO.setIndexNum(smartLockPwd.getPwdIndexNum());
            // 熙照
            if (authType == 3) {
                smartLockVO.setTimes(value);
            } else {
                smartLockVO.setTimes(-1);
            }

            // 亚略特
            if (smartLock.getBrandId() == 3L) {
                if (smartLockPwdRepository.findByLockAuthId(lockAuthId) == null) {// 新增
                    smartLockPwd.setfAppUserId(GenerateNiceString.generateNiceString());
                    YltAuthorizationVO yltVO = new YltAuthorizationVO();
                    yltVO.setfLockMAC(smartLock.getMac());
                    yltVO.setfAppUserID(smartLockPwd.getfAppUserId());
                    yltVO.setfBeginDate(smartLockVO.getStartTime());
                    yltVO.setfEndDate(smartLockVO.getEndTime());
                    yltVO.setfOpenByPassword(1);
                    yltVO.setfOpenByIDCard(0);
                    yltVO.setfOpenByBLE(0);
                    yltVO.setfOpenByFinger(0);
                    yltVO.setfOpenByICCard(0);
                    yltVO.setfOpenPassword(smartLockPwd.getPassword());
                    smartLockVO.setYltAuth(yltVO);
                } else {// 修改
                    smartLockVO.setfAuthorizationID(smartLockPwd.getfAuthorizationId());
                }
            }
            ResultBean<String> stringResultBean = smartLockBrandService.operationPassword(smartLockVO, smartLockPwd,
                    smartLock.getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();
            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authPwd---> " + resultData);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
                // throw new BizException(msg);
            } else {
                log.info("LockAppService authPwd---> callBack={}", resultData);
                // 生成密码授权明细
                if (smartLock.getBrandId() == 3L && smartLockPwdRepository.findByLockAuthId(lockAuthId) == null) {// 亚略特 新增
                    smartLockPwd.setfAuthorizationId(resultData);
                }
                if (smartLock.getBrandId() == 5L) {
                    smartLockPwd.setIdentification(resultData);
                }
                if (smartLock.getBrandId() == 6L) {
                    Long id = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
                    smartLockPwd.setReturnPwdId(id);
                }
                if (smartLock.getBrandId() == 8L) {
                    String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                    smartLockPwd.setIdentification(phoneNo);
                    String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                    smartLockPwd.setfAuthorizationId(keyId);
                }
                SmartLockPwd newSmartLockPwd = new SmartLockPwd();
                BeanUtils.copyProperties(smartLockPwd, newSmartLockPwd);
                if (smartLock.getBrandId() != 5L) {
                    smartLockPwdRepository.save(smartLockPwd);
                }

                // 更新用户授权明细状态
                updateSmartLockAuthStatus(smartLock.getBrandId(), 1, 1, smartLockAuth);
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                // 发送短信
                String str = smsService.sendTemplateMsgSms(mobile, smartLockPwd.getPassword());
                // 缓存临时密码
                redisService.putAuthTemporaryPwdMinute(mobile, smartLockPwd.getPassword(), smartLockAuth.getHouseId(), minute);
                if (str.equals("success")) {
                    // 如果是承租人授权，更新公租房锁授权状态
                    if (house.getHouseNature() == 1) {
                        if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                            String houseId = smartLockAuth.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 1);
                        }
                    }

                    if (passwordType == 0) {
                        // 短信发送次数+1
                        String plus = "";
                        if (StringUtils.isNotBlank(redis)) {
                            int num = Integer.parseInt(redis);
                            plus = String.valueOf(num + 1);
                        } else {
                            plus = "1";
                        }
                        redisTemplate.opsForValue().set("repeatPwd:" + mobile, plus, DateUtils.getTimeMillis(), TimeUnit.SECONDS);

                    }

                    return ResultBean.successfulResultWithMsg("指令下发成功", null);
                } else {
                    log.error(StrUtil.format("指令下发成功，短信通知失败, {}", mobile));
                    return ResultBean.failedResultWithMsg("发送短信次数已经超过当日上限。");
                }
            }
        } catch (Exception e) {
            log.error("LockAppService authPwd Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 授权密码
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  授权用户id
     * @param lockId      智能锁id
     * @param type        密码类型：1自定义密码 2 授权密码 3 临时密码
     * @param password    自定义密码
     * @param authType    设置方式：1永久 2时间期限 3次数
     * @param value       输入值
     * @return
     */
    @Transactional
    public ResultBean<Object> authPwd(String accessToken, Long lockAuthId, Long lockId, Integer type, String password,
                                      Integer authType, Integer value) {
        log.info(
                "LockAppService authPwd, accessToken={}, lockAuthId={}, lockId={}, type{}, password={}, authType={}, value={}",
                accessToken, lockAuthId, lockId, type, password, authType, value);
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("密码类型不存在");
            }
            if (authType == null) {
                return ResultBean.failedResultOfParamWithMsg("授权方式不存在");
            }

            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            Integer loginType = token.getLoginType();


            // 授权前更新未激活智能锁sn值
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }

            SmartLock smartLock = lockOptional.get();

            if (smartLock.getBrandId() == 8L) {
                if (authType == 3) {
                    return ResultBean.failedResultOfParamWithMsg("没有次数密码");
                }
            }
            SmartLockPwd byLockAuthIdAndType = null;
            if (type == 1) {
                byLockAuthIdAndType = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 2);
            } else if (type == 2) {
                byLockAuthIdAndType = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 1);
            }
            if (ObjectUtil.isNotEmpty(byLockAuthIdAndType) && !smartLock.getBrandId().equals(3L)) {
                return ResultBean.failedResultWithMsg("授权密码只能授权一种！");
            }


            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();
            String mobile = smartLockAuth.getMobile();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }
            House house = houseOptional.get();

            // 获取短信发送次数
            String redis = redisTemplate.opsForValue().get("repeatPwd:" + mobile);
            // if (StringUtils.isNotBlank(redis)) {
            //    int num = Integer.parseInt(redis);
            //    if (type == 2 && num >= 4) {
            //        return ResultBean.failedResultWithMsg("已超过设置上限，请明天再试");
            //    }
            //}

            String mac = smartLock.getMac();
            String sn = smartLock.getSn();
            if (StringUtils.isBlank(sn)) {
                ResultBean<String> resultBean = smartLockBrandService.getSnByMac(mac, smartLock.getHouseId(),
                        smartLock.getBrandId());
                if (resultBean == null) {
                    return ResultBean.failedResultOfParamWithMsg("智能锁ID为空, 已重新注册, 稍后重试");
                }
                String resultSn = resultBean.getResultData();
                if (StringUtils.isBlank(resultSn)) {
                    return ResultBean.failedResultWithMsg("设备状态异常");
                } else {
                    smartLock.setSn(resultSn);
                    smartLock.setMechineStatus(1);
                    smartLockRepository.save(smartLock);
                }
            }

            /**
             * 验证智能锁，或者 密码， 指纹 身份证 CPU卡  蓝牙 是否冻结
             * true  代表未冻结
             * false  代表已冻结
             * @param lockId 智能锁id
             * @param lockAuthId 用户授权id
             */
            //授权临时密码提示  bug:1706
            // bug修复有误
           Boolean FreezeBoolean = lockCurrencyService.freezeOrNot(lockId, lockAuthId);
           if (!FreezeBoolean) {
               return ResultBean.failedResultWithMsg("授权失败，智能锁已冻结或授权已冻结！");
           }

            // SmartLockPwd smartLockPwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
            SmartLockPwd smartLockPwd;
            smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 1);
            if (smartLockPwd == null) {
                smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 2);
            }
            if (smartLockPwd == null) {// 新增
                smartLockPwd = new SmartLockPwd();
                smartLockPwd.setLockAuthId(lockAuthId);
                smartLockPwd.setLockId(lockId);
                smartLockPwd.setCreateTime(new Date());
                smartLockPwd.setLastUpdateTime(smartLockPwd.getCreateTime());

                // 密码序号
                List<SmartLockPwd> smartLockPwds = smartLockPwdRepository.findByLockId(lockId);
                if (smartLockPwds != null && !smartLockPwds.isEmpty()) {// 已存在序号
                    List<Integer> indexs = smartLockPwds.stream().filter(vo -> vo.getPwdIndex() != null)
                            .map(SmartLockPwd::getPwdIndex).distinct().collect(Collectors.toList());
                    Integer max = Collections.max(indexs);
                    if (max == 49) {
                        // 排除已有序号，取1-49间的最小值
                        List<Integer> list = new ArrayList<>();
                        for (int i = 0, j = 49; i < j; ++i) {
                            list.add(i + 1);
                        }
                        for (Integer i : indexs) {
                            list.remove(i);
                        }
                        Integer min = Collections.min(list);
                        smartLockPwd.setPwdIndex(min);
                    } else {
                        smartLockPwd.setPwdIndex(max + 1);// 取智能锁密码序号最大值 +1
                    }
                } else {// 没有序号
                    smartLockPwd.setPwdIndex(1);
                }
            } else {// 修改
                // return ResultBean.failedResultWithMsg("该把锁已经授权密码");
                smartLockPwd.setLastUpdateTime(new Date());
            }

            if (smartLock.getBrandId() == 4L) {
                // 新增天网互联密码标识
                String identification = smartLockPwd.getIdentification();
                if (StrUtil.isEmpty(identification)) {
                    identification = "L" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
                }
                smartLockPwd.setIdentification(identification);
            }
            smartLockPwd.setType(type);
            smartLockPwd.setAuthType(authType);
            smartLockPwd.setAuthTime(new Date());
            smartLockPwd.setStatus(0);// 0待执行
            if (smartLock.getBrandId() == 3L) {
                smartLockPwd.setStatus(1);
            }

            if (type == 1) {
                smartLockPwd.setPassword(password);
            } else if (type == 2) {
                smartLockPwd.setPassword(RandomNoUtils.getRandomNum(6));
            } else if (type == 3) {
                smartLockPwd.setPassword(RandomNoUtils.getRandomNum(6));
            }

            // 密码设置方式
            if (authType == 1) {// 永久
                smartLockPwd.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                smartLockPwd.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockPwd.setLimitDay(DateUtils.daysBetween(smartLockPwd.getStartTime(), smartLockPwd.getEndTime()));
            } else if (authType == 2) {// 时间期限
                smartLockPwd.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                smartLockPwd.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockPwd.setLimitDay(value);
            } else if (authType == 3) {// 次数
                smartLockPwd.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                smartLockPwd.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockPwd.setLimitDay(DateUtils.daysBetween(smartLockPwd.getStartTime(), smartLockPwd.getEndTime()));
                smartLockPwd.setAuthorNumber(value);
                smartLockPwd.setTimes(value);
            }

            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            // 新增天网互联密码标识
            smartLockVO.setIdentification(smartLockPwd.getIdentification());
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setStartTime(DateUtils.format(smartLockPwd.getStartTime(), DateUtils.FORMAT_14));
            smartLockVO.setEndTime(DateUtils.format(smartLockPwd.getEndTime(), DateUtils.FORMAT_14));
            if (smartLock.getBrandId() == 3L) {// 亚略特
                smartLockVO.setStartTime(DateUtils.format(smartLockPwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                smartLockVO.setEndTime(DateUtils.format(smartLockPwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
            }
            smartLockVO.setPassword(smartLockPwd.getPassword());
            if (authType == 1 || authType == 2) {
                smartLockVO.setAuthType("2");
            } else if (authType == 3) {
                smartLockVO.setAuthType("5");
                smartLockVO.setTimes(smartLockPwd.getTimes());
            }
            smartLockVO.setIndex(smartLockPwd.getPwdIndex());
            smartLockVO.setDevMac(smartLock.getMac());
            smartLockVO.setAuthInfoId(lockAuthId);
            smartLockVO.setIndexNum(smartLockPwd.getPwdIndexNum());
            // 熙照
            if (authType == 3) {
                smartLockVO.setTimes(value);
            } else {
                smartLockVO.setTimes(-1);
            }

            // 亚略特
            if (smartLock.getBrandId().equals(3L)) {
                if (smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, type) == null) {// 新增
                    smartLockPwd.setfAppUserId(GenerateNiceString.generateNiceString());
                    YltAuthorizationVO yltVO = new YltAuthorizationVO();
                    yltVO.setfLockMAC(smartLock.getMac());
                    yltVO.setfAppUserID(smartLockPwd.getfAppUserId());
                    yltVO.setfBeginDate(smartLockVO.getStartTime());
                    yltVO.setfEndDate(smartLockVO.getEndTime());
                    yltVO.setfOpenByPassword(1);
                    yltVO.setfOpenByIDCard(0);
                    yltVO.setfOpenByBLE(0);
                    yltVO.setfOpenByFinger(0);
                    yltVO.setfOpenByICCard(0);
                    yltVO.setfOpenPassword(smartLockPwd.getPassword());
                    smartLockVO.setYltAuth(yltVO);
                } else {// 修改
                    smartLockVO.setfAuthorizationID(smartLockPwd.getfAuthorizationId());
                }
            }
            ResultBean<String> stringResultBean = smartLockBrandService.operationPassword(smartLockVO, smartLockPwd,
                    smartLock.getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();
            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authPwd---> " + resultData);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
                // throw new BizException(msg);
            } else {
                log.info("LockAppService authPwd---> callBack={}", resultData);
                // 生成密码授权明细
                if (smartLock.getBrandId() == 3L && smartLockPwdRepository.findByLockAuthId(lockAuthId) == null) {// 亚略特 新增
                    smartLockPwd.setfAuthorizationId(resultData);
                }

                if (smartLock.getBrandId() == 5L ) {
                    smartLockPwd.setIdentification(resultData);
                }
                if (smartLock.getBrandId() == 8L ) {
                    String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                    smartLockPwd.setIdentification(phoneNo);
                    String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                    smartLockPwd.setfAuthorizationId(keyId);
                }
                // SmartLockPwd newSmartLockPwd = new SmartLockPwd();
                // BeanUtils.copyProperties(smartLockPwd, newSmartLockPwd);
                if (smartLock.getBrandId() == 6L) {
                    Long id = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
                    smartLockPwd.setReturnPwdId(id);
                }
                smartLockPwdRepository.save(smartLockPwd);

                // 更新用户授权明细状态
                updateSmartLockAuthStatus(smartLock.getBrandId(), 1, 1, smartLockAuth);
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                // 发送短信
                String str = smsService.sendTemplateMsgSms(mobile, smartLockPwd.getPassword());
                if (authType == 2 && loginType == UserLoginTypeEnum.CONSUMER.getValue()) {
                    redisService.putAuthTemporaryPwd(mobile, smartLockPwd.getPassword(), smartLockAuth.getHouseId(), smartLockPwd.getLimitDay());
                }

                if (loginType == UserLoginTypeEnum.ENTERPRISE.getValue()){
                    redisService.deleteAuthTemporaryPwd(mobile, smartLockPwd.getPassword(), smartLockAuth.getHouseId());
                }

                if (str.equals("success")) {
                    // 如果是承租人授权，更新公租房锁授权状态
                    if (house.getHouseNature() == 1) {
                        if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                            String houseId = smartLockAuth.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 1);
                        }
                    }

                    // 短信发送次数+1
                    String plus = "";
                    if (StringUtils.isNotBlank(redis)) {
                        int num = Integer.parseInt(redis);
                        plus = String.valueOf(num + 1);
                    } else {
                        plus = "1";
                    }
                    redisTemplate.opsForValue().set("repeatPwd:" + mobile, plus, DateUtils.getTimeMillis(), TimeUnit.SECONDS);

                    return ResultBean.successfulResultWithMsg("指令下发成功", null);
                } else {
                    log.error(StrUtil.format("指令下发成功，短信通知失败, {}", mobile));
                    return ResultBean.failedResultWithMsg("发送短信次数已经超过当日上限。");
                }
            }
        } catch (Exception e) {
            log.error("LockAppService authPwd Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 授权卡
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  授权用户id
     * @param lockId      智能锁id
     * @param type        卡类型：1身份证 2CPU卡
     * @param cardNumber  cpu卡号/身份证号码
     * @param cardId      卡号id
     * @param authType    设置方式：1永久 2时间期限 3次数
     * @param value       输入值
     * @return
     */
    @Transactional
    public ResultBean<Object> authCard(String accessToken, Long lockAuthId, Long lockId, Integer type,
                                       String cardNumber, String cardId, Integer authType, Integer value) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("id不存在");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("卡类型不存在");
            }
            if (StringUtils.isBlank(cardNumber)) {
                return ResultBean.failedResultOfParamWithMsg("卡号不存在");
            }
            if (StringUtils.isBlank(cardId)) {
                return ResultBean.failedResultOfParamWithMsg("卡号id不存在");
            }
            if (authType == null) {
                return ResultBean.failedResultOfParamWithMsg("授权方式不存在");
            }
            if (authType == 3 && value == null) {
                return ResultBean.failedResultOfParamWithMsg("次数为空");
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }
            House house = houseOptional.get();

            // 授权前更新未激活智能锁sn值
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();
            String mac = smartLock.getMac();
            String sn = smartLock.getSn();
            if (StringUtils.isBlank(sn)) {
                ResultBean<String> resultBean = smartLockBrandService.getSnByMac(mac, smartLock.getHouseId(),
                        smartLock.getBrandId());
                if (resultBean == null) {
                    return ResultBean.failedResultOfParamWithMsg("智能锁ID为空, 已重新注册, 稍后重试");
                }
                String resultSn = resultBean.getResultData();
                if (StringUtils.isBlank(resultSn)) {
                    return ResultBean.failedResultWithMsg("设备状态异常");
                } else {
                    smartLock.setSn(resultSn);
                    smartLock.setMechineStatus(1);
                    smartLockRepository.save(smartLock);
                }
            }
            /**
             * 验证智能锁，或者 密码， 指纹 身份证 CPU卡  蓝牙 是否冻结
             * true  代表未冻结
             * false  代表已冻结
             * @param lockId 智能锁id
             * @param lockAuthId 用户授权id
             */
            Boolean FreezeBoolean = lockCurrencyService.freezeOrNot(lockId, lockAuthId);
            if (!FreezeBoolean) {
                return ResultBean.failedResultWithMsg("授权失败，智能锁已冻结或授权已冻结！");
            }
            Date date = new Date();
            SmartLockCard smartLockCard = smartLockCardRepository.findByLockAuthIdAndType(lockAuthId, type);
            if (smartLockCard == null) {// 新增
                smartLockCard = new SmartLockCard();
                smartLockCard.setLockId(lockId);
                smartLockCard.setLockAuthId(lockAuthId);
                smartLockCard.setType(type);
                smartLockCard.setCreateTime(new Date());

                // 卡序号:50-100
                List<SmartLockCard> smartLockCards = smartLockCardRepository.findByLockId(lockId);
                if (smartLockCards != null && !smartLockCards.isEmpty()) {// 已存在序号
                    List<Integer> indexs = smartLockCards.stream().filter(vo -> vo.getCardIndex() != null)
                            .map(SmartLockCard::getCardIndex).distinct().collect(Collectors.toList());
                    Integer max = Collections.max(indexs);
                    if (max == 100) {
                        // 排除已有序号，取50-100间的最小值
                        List<Integer> list = new ArrayList<>();
                        for (int i = 49, j = 100; i < j; ++i) {
                            list.add(i + 1);
                        }
                        for (Integer i : indexs) {
                            list.remove(i);
                        }
                        Integer min = Collections.min(list);
                        smartLockCard.setCardIndex(min);
                    } else {
                        smartLockCard.setCardIndex(max + 1);// 取智能锁密码序号最大值 +1
                    }
                } else {// 没有序号
                    smartLockCard.setCardIndex(50);
                }
            }

            if (smartLock.getBrandId() == 2) {
                int length = cardId.length();
                StringBuffer cardBuf = new StringBuffer();
                if (length < 10) {
                    for (int i = 0; i < 10 - length; i++) {
                        cardBuf.append("0");
                    }
                } else if (length > 10 && length < 20) {
                    for (int i = 0; i < 20 - length; i++) {
                        cardBuf.append("0");
                    }
                }
                cardId = cardBuf.toString() + cardId;
            }

            if (smartLock.getBrandId() == 4L) {
                // 新增天网互联密码标识
                String identification = smartLockCard.getIdentification();
                if (StrUtil.isEmpty(identification)) {
                    identification = "L" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
                }
                smartLockCard.setIdentification(identification);
            }
            smartLockCard.setAuthType(authType);
            smartLockCard.setAuthTime(date);
            smartLockCard.setCardNumber(cardNumber);
            smartLockCard.setCardId(cardId);
            smartLockCard.setStatus(0);
            if (smartLock.getBrandId() == 3L || smartLock.getBrandId() == 4L) {
                smartLockCard.setStatus(1);
            }

            // 卡设置方式
            if (authType == 1) {// 永久
                smartLockCard.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                smartLockCard.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockCard.setLimitDay(DateUtils.daysBetween(smartLockCard.getStartTime(), smartLockCard.getEndTime()));
            } else if (authType == 2) {// 时间期限
                smartLockCard.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                smartLockCard.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockCard.setLimitDay(value);
            } else if (authType == 3) { // 次数
                smartLockCard.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                smartLockCard.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockCard
                        .setLimitDay(DateUtils.daysBetween(smartLockCard.getStartTime(), smartLockCard.getEndTime()));
                smartLockCard.setAuthorNumber(value);
                smartLockCard.setTimes(value);
            }

            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setIdentification(smartLockCard.getIdentification());
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setCardIndex(smartLockCard.getCardIndex());
            smartLockVO.setCardId(smartLockCard.getCardId());
            smartLockVO.setAuthInfoId(lockAuthId);
            smartLockVO.setCardType(type);
            smartLockVO.setStartTime(DateUtils.format(smartLockCard.getStartTime(), DateUtils.FORMAT_14));
            smartLockVO.setEndTime(DateUtils.format(smartLockCard.getEndTime(), DateUtils.FORMAT_14));
            if (smartLock.getBrandId() == 3L) {// 亚略特
                smartLockVO.setStartTime(DateUtils.format(smartLockCard.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                smartLockVO.setEndTime(DateUtils.format(smartLockCard.getEndTime(), DateUtils.FORMAT_DATETIME_14));
            }
            smartLockVO.setDevMac(smartLock.getMac());
            smartLockVO.setCardIndexNum(smartLockCard.getCardIndexNum());
            if (authType == 3) {
                smartLockVO.setTimes(value);
            } else {
                // 不限次数
                smartLockVO.setTimes(-1);
            }

            // 亚略特
            if (smartLock.getBrandId() == 3L) {
                if (smartLockCardRepository.findByLockAuthIdAndType(lockAuthId, type) == null) {// 新增
                    smartLockCard.setfAppUserId(GenerateNiceString.generateNiceString());
                } else {// 修改
                    smartLockVO.setfAuthorizationID(smartLockCard.getfAuthorizationId());
                }
                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                yltVO.setfLockMAC(smartLock.getMac());
                yltVO.setfAppUserID(smartLockCard.getfAppUserId());
                yltVO.setfBeginDate(smartLockVO.getStartTime());
                yltVO.setfEndDate(smartLockVO.getEndTime());
                yltVO.setfOpenByPassword(0);
                yltVO.setfOpenByBLE(0);
                yltVO.setfOpenByFinger(0);
                if (type == 1) {
                    yltVO.setfOpenByIDCard(1);
                    yltVO.setfOpenByICCard(0);
                } else {
                    yltVO.setfOpenByIDCard(0);
                    yltVO.setfOpenByICCard(1);
                }
                yltVO.setfIDCardID(cardId);
                yltVO.setfIDCardNumber(cardNumber);
                smartLockVO.setYltAuth(yltVO);
            }

            ResultBean<String> stringResultBean = smartLockBrandService.operationCardPassword(smartLockVO,
                    smartLockCard, smartLock.getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authPwd---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService authPwd---> callBack={}", resultData);
                // 生成卡授权明细
                if (smartLock.getBrandId() == 3L || smartLock.getBrandId() == 5L ) {// 亚略特
                    smartLockCard.setfAuthorizationId(resultData);
                }
                smartLockCard.setIdentification(resultData);

                // 新增六代智能锁厂商门卡授权id
                if (smartLock.getBrandId() == 6L) {
                    Long id = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
                    smartLockCard.setReturnCardId(id);
                }
                if (smartLock.getBrandId() == 8L) {
                    String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                    smartLockCard.setIdentification(phoneNo);
                    String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                    smartLockCard.setfAuthorizationId(keyId);
                }
                smartLockCardRepository.save(smartLockCard);

                // 更新用户授权明细状态
                if (type == 1) {
                    updateSmartLockAuthStatus(smartLock.getBrandId(), 2, 1, smartLockAuth);
                } else {
                    updateSmartLockAuthStatus(smartLock.getBrandId(), 3, 1, smartLockAuth);
                }
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                // 发送短信
                String str = smsService.sendTemplateSms(smartLockAuth.getMobile(), smsConfig.getAuthTemplateCode());
                if (str.equals("success")) {
                    // 如果是承租人授权，更新公租房锁授权状态
                    if (house.getHouseNature() == 1) {
                        if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                            String houseId = smartLockAuth.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 1);
                        }
                    }
                    return ResultBean.successfulResultWithMsg("指令下发成功", null);
                } else {
                    return ResultBean.failedResultWithMsg("指令下发成功，短信通知失败");
                }
            }

        } catch (Exception e) {
            log.error("LockAppService authCard Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 授权卡(后管调用)
     */
    @Transactional
    public ResultBean<Object> authCards(String lockAuthIds, String lockIds, String types,
                                        String cardNumber, String cardId, String authTypes, String values) {
        Long lockAuthId = StringUtils.isNotBlank(lockAuthIds) == true ? Long.parseLong(lockAuthIds) : null;
        Long lockId = StringUtils.isNotBlank(lockIds) == true ? Long.parseLong(lockIds) : null;
        Integer type = StringUtils.isNotBlank(types) == true ? Integer.valueOf(types) : null;

        Integer authType = StringUtils.isNotBlank(authTypes) == true ? Integer.parseInt(authTypes) : null;
        Integer value = StringUtils.isNotBlank(values) == true ? Integer.parseInt(values) : null;

        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("id不存在");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("卡类型不存在");
            }
            if (StringUtils.isBlank(cardNumber)) {
                return ResultBean.failedResultOfParamWithMsg("卡号不存在");
            }
            if (StringUtils.isBlank(cardId)) {
                return ResultBean.failedResultOfParamWithMsg("卡号id不存在");
            }
            if (authType == null) {
                return ResultBean.failedResultOfParamWithMsg("授权方式不存在");
            }
            if (authType == 3 && value == null) {
                return ResultBean.failedResultOfParamWithMsg("次数为空");
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }
            House house = houseOptional.get();

            // 授权前更新未激活智能锁sn值
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();
            String mac = smartLock.getMac();
            String sn = smartLock.getSn();
            if (StringUtils.isBlank(sn)) {
                ResultBean<String> resultBean = smartLockBrandService.getSnByMac(mac, smartLock.getHouseId(),
                        smartLock.getBrandId());
                if (resultBean == null) {
                    return ResultBean.failedResultOfParamWithMsg("智能锁ID为空, 已重新注册, 稍后重试");
                }
                String resultSn = resultBean.getResultData();
                if (StringUtils.isBlank(resultSn)) {
                    return ResultBean.failedResultWithMsg("设备状态异常");
                } else {
                    smartLock.setSn(resultSn);
                    smartLock.setMechineStatus(1);
                    smartLockRepository.save(smartLock);
                }
            }

            /**
             * 验证智能锁，或者 密码， 指纹 身份证 CPU卡  蓝牙 是否冻结
             * true  代表未冻结
             * false  代表已冻结
             * @param lockId 智能锁id
             * @param lockAuthId 用户授权id
             */
            Boolean FreezeBoolean = lockCurrencyService.freezeOrNot(lockId, lockAuthId);
            if (!FreezeBoolean) {
                return ResultBean.failedResultWithMsg("授权失败，智能锁已冻结或授权已冻结！");
            }

            Date date = new Date();
            SmartLockCard smartLockCard = smartLockCardRepository.findByLockAuthIdAndType(lockAuthId, type);
            if (smartLockCard == null) {// 新增
                smartLockCard = new SmartLockCard();
                smartLockCard.setLockId(lockId);
                smartLockCard.setLockAuthId(lockAuthId);
                smartLockCard.setType(type);
                smartLockCard.setCreateTime(new Date());

                // 卡序号:50-100
                List<SmartLockCard> smartLockCards = smartLockCardRepository.findByLockId(lockId);
                if (smartLockCards != null && !smartLockCards.isEmpty()) {// 已存在序号
                    List<Integer> indexs = smartLockCards.stream().filter(vo -> vo.getCardIndex() != null)
                            .map(SmartLockCard::getCardIndex).distinct().collect(Collectors.toList());
                    Integer max = Collections.max(indexs);
                    if (max == 100) {
                        // 排除已有序号，取50-100间的最小值
                        List<Integer> list = new ArrayList<>();
                        for (int i = 49, j = 100; i < j; ++i) {
                            list.add(i + 1);
                        }
                        for (Integer i : indexs) {
                            list.remove(i);
                        }
                        Integer min = Collections.min(list);
                        smartLockCard.setCardIndex(min);
                    } else {
                        smartLockCard.setCardIndex(max + 1);// 取智能锁密码序号最大值 +1
                    }
                } else {// 没有序号
                    smartLockCard.setCardIndex(50);
                }
            }

            if (smartLock.getBrandId() == 2) {
                int length = cardId.length();
                StringBuffer cardBuf = new StringBuffer();
                if (length < 10) {
                    for (int i = 0; i < 10 - length; i++) {
                        cardBuf.append("0");
                    }
                } else if (length > 10 && length < 20) {
                    for (int i = 0; i < 20 - length; i++) {
                        cardBuf.append("0");
                    }
                }
                cardId = cardBuf.toString() + cardId;
            }
            // 新增天网互联密码标识
            String identification = smartLockCard.getIdentification();
            if (StrUtil.isEmpty(identification)) {
                identification = "L" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
            }
            smartLockCard.setIdentification(identification);
            smartLockCard.setAuthType(authType);
            smartLockCard.setAuthTime(date);
            smartLockCard.setCardNumber(cardNumber);
            smartLockCard.setCardId(cardId);
            smartLockCard.setStatus(0);
            if (smartLock.getBrandId() == 3L) {
                smartLockCard.setStatus(1);
            }

            // 卡设置方式
            if (authType == 1) {// 永久
                smartLockCard.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                smartLockCard.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockCard
                        .setLimitDay(DateUtils.daysBetween(smartLockCard.getStartTime(), smartLockCard.getEndTime()));
            } else if (authType == 2) {// 时间期限
                smartLockCard.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                smartLockCard.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockCard.setLimitDay(value);
            } else if (authType == 3) { // 次数
                smartLockCard.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                smartLockCard.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockCard
                        .setLimitDay(DateUtils.daysBetween(smartLockCard.getStartTime(), smartLockCard.getEndTime()));
                smartLockCard.setAuthorNumber(value);
                smartLockCard.setTimes(value);
            }

            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setIdentification(smartLockCard.getIdentification());
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setCardIndex(smartLockCard.getCardIndex());
            smartLockVO.setCardId(smartLockCard.getCardId());
            smartLockVO.setAuthInfoId(lockAuthId);
            smartLockVO.setCardType(type);
            smartLockVO.setStartTime(DateUtils.format(smartLockCard.getStartTime(), DateUtils.FORMAT_14));
            smartLockVO.setEndTime(DateUtils.format(smartLockCard.getEndTime(), DateUtils.FORMAT_14));
            if (smartLock.getBrandId() == 3L) {// 亚略特
                smartLockVO.setStartTime(DateUtils.format(smartLockCard.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                smartLockVO.setEndTime(DateUtils.format(smartLockCard.getEndTime(), DateUtils.FORMAT_DATETIME_14));
            }
            smartLockVO.setDevMac(smartLock.getMac());
            smartLockVO.setCardIndexNum(smartLockCard.getCardIndexNum());
            if (authType == 3) {
                smartLockVO.setTimes(value);
            } else {
                // 不限次数
                smartLockVO.setTimes(-1);
            }

            // 亚略特
            if (smartLock.getBrandId() == 3L) {
                if (smartLockCardRepository.findByLockAuthIdAndType(lockAuthId, type) == null) {// 新增
                    smartLockCard.setfAppUserId(GenerateNiceString.generateNiceString());
                } else {// 修改
                    smartLockVO.setfAuthorizationID(smartLockCard.getfAuthorizationId());
                }
                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                yltVO.setfLockMAC(smartLock.getMac());
                yltVO.setfAppUserID(smartLockCard.getfAppUserId());
                yltVO.setfBeginDate(smartLockVO.getStartTime());
                yltVO.setfEndDate(smartLockVO.getEndTime());
                yltVO.setfOpenByPassword(0);
                yltVO.setfOpenByBLE(0);
                yltVO.setfOpenByFinger(0);
                if (type == 1) {
                    yltVO.setfOpenByIDCard(1);
                    yltVO.setfOpenByICCard(0);
                } else {
                    yltVO.setfOpenByIDCard(0);
                    yltVO.setfOpenByICCard(1);
                }
                yltVO.setfIDCardID(cardId);
                yltVO.setfIDCardNumber(cardNumber);
                smartLockVO.setYltAuth(yltVO);
            }

            ResultBean<String> stringResultBean = smartLockBrandService.operationCardPassword(smartLockVO,
                    smartLockCard, smartLock.getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authPwd---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService authPwd---> callBack={}", resultData);
                // 生成卡授权明细
                if (smartLock.getBrandId() == 3L || smartLock.getBrandId() == 5L ) {// 亚略特
                    smartLockCard.setfAuthorizationId(resultData);
                }
                // 新增六代智能锁厂商门卡授权id
                if (smartLock.getBrandId() == 6L) {// 亚略特
                    Long id = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
                    smartLockCard.setReturnCardId(id);
                }
                if (smartLock.getBrandId() == 8L) {
                    String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                    smartLockCard.setIdentification(phoneNo);
                    String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                    smartLockCard.setfAuthorizationId(keyId);
                }
                smartLockCard.setIdentification(resultData);
                smartLockCardRepository.save(smartLockCard);

                // 更新用户授权明细状态
                if (type == 1) {
                    updateSmartLockAuthStatus(smartLock.getBrandId(), 2, 1, smartLockAuth);
                } else {
                    updateSmartLockAuthStatus(smartLock.getBrandId(), 3, 1, smartLockAuth);
                }
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                // 发送短信
                String str = smsService.sendTemplateSms(smartLockAuth.getMobile(), smsConfig.getEmpowerTemplateCode());
                if (str.equals("success")) {
                    // 如果是承租人授权，更新公租房锁授权状态
                    if (house.getHouseNature() == 1) {
                        if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                            String houseId = smartLockAuth.getHouseId();
                            houseRepository.updateLockStatusById(houseId, 1);
                        }
                    }
                    return ResultBean.successfulResultWithMsg("指令下发成功", null);
                } else {
                    return ResultBean.failedResultWithMsg("指令下发成功，短信通知失败");
                }
            }

        } catch (Exception e) {
            log.error("LockAppService authCard Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 删除授权密码
     *
     * @param lockAuthId 授权用户id
     * @param lockId     智能锁id
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ResultBean<Object> deletePwdAuth(Long lockAuthId, Long lockId) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            // SmartLockPwd smartLockPwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
            SmartLockPwd smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 1);
            if (smartLockPwd == null) {
                smartLockPwd = smartLockPwdRepository.findByLockAuthIdAndType(lockAuthId, 2);
            }
            if (smartLockPwd == null) {
                return ResultBean.failedResultWithMsg("密码授权明细不存在");
            }

            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setIndex(smartLockPwd.getPwdIndex());
            smartLockVO.setAuthInfoId(lockAuthId);

            // 六代智能锁厂商密码授权id
            if (smartLock.getBrandId() == 6L) {
                smartLockVO.setReturnPwdId(smartLockPwd.getReturnPwdId());
            }
            smartLockVO.setIdentification(smartLockPwd.getIdentification());
            // 亚略特
            smartLockVO.setfAuthorizationID(smartLockPwd.getfAuthorizationId());

            ResultBean<String> stringResultBean = smartLockBrandService.clearPassword(smartLockVO,
                    smartLock.getBrandId(), "code", lockAuthId);
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService deletePwdAuth---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService deletePwdAuth---> callBack={}", resultData);
                // 删除密码授权   新增了密码生成方式:1自定义 2系统生成 3生成临时密码，需要根据类型进行删除，不需要删除3临时密码；

                smartLockPwdRepository.deleteByLockAuthId(lockAuthId);
                // smartLockPwdRepository.deleteByLockAuthIdAndType(lockAuthId, 1);
                // smartLockPwdRepository.deleteByLockAuthIdAndType(lockAuthId, 2);


                // 更新用户授权明细状态
                updateSmartLockAuthStatus(smartLock.getBrandId(), 1, 2, smartLockAuth);
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                return ResultBean.successfulResultWithMsg("指令下发成功", null);
            }
        } catch (Exception e) {
            log.error("LockAppService deletePwdAuth Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 删除授权卡
     *
     * @param lockAuthId 授权用户id
     * @param lockId     智能锁id
     * @param type       卡类型：1身份证 2CPU卡
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ResultBean<Object> deleteCardAuth(Long lockAuthId, Long lockId, Integer type) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("卡类型不存在");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            SmartLockCard smartLockCard = smartLockCardRepository.findByLockAuthIdAndType(lockAuthId, type);
            if (smartLockCard == null) {
                return ResultBean.failedResultWithMsg("卡授权明细不存在");
            }

            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setIndex(smartLockCard.getCardIndex());
            smartLockVO.setEndTime(String.valueOf(smartLockCard.getEndTime()));
            smartLockVO.setAuthInfoId(lockAuthId);
            smartLockVO.setCardType(type);
            smartLockVO.setCardIndexNum(smartLockCard.getCardIndexNum());
            smartLockVO.setIdentification(smartLockCard.getIdentification());
            // 亚略特
            smartLockVO.setfAuthorizationID(smartLockCard.getfAuthorizationId());


            // 六代智能锁厂商密码授权id
            if (smartLock.getBrandId() == 6L) {
                smartLockVO.setReturnCardId(smartLockCard.getReturnCardId());
            }

            ResultBean<String> stringResultBean = smartLockBrandService.clearCard(smartLockVO, smartLock.getBrandId(),
                    "card");
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService deleteCardAuth---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService deleteCardAuth---> callBack={}", resultData);
                // 删除卡授权
                smartLockCardRepository.deleteByLockAuthIdAndType(lockAuthId, type);

                // 更新用户授权明细状态
                if (type == 1) {
                    updateSmartLockAuthStatus(smartLock.getBrandId(), 2, 2, smartLockAuth);
                } else {
                    updateSmartLockAuthStatus(smartLock.getBrandId(), 3, 2, smartLockAuth);
                }
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                return ResultBean.successfulResultWithMsg("指令下发成功", null);
            }
        } catch (Exception e) {
            log.error("LockAppService deleteCardAuth Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 授权指纹
     *
     * @param accessToken
     * @param lockAuthId  授权ID
     * @param lockId      锁ID
     * @param type        密码类型：1自定义 2 授权
     * @param fingerprint 指纹数据
     * @param authType    设置方式：1永久 2时间期限 3次数
     * @param value
     * @return
     * @author shun
     * @date 2021年7月6日
     */
    @Transactional
    public ResultBean<Object> authFingerprint(String accessToken, Long lockAuthId, Long lockId, Integer type,
                                              String fingerprint, Integer authType, Integer value, Boolean flag) {
        log.info(
                "LockAppService authFingerprint, accessToken={}, lockAuthId={}, lockId={}, type{}, fingerprint={}, authType={}, value={}",
                accessToken, lockAuthId, lockId, type, fingerprint, authType, value);
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("指纹类型不存在");
            }
            if (authType == null) {
                return ResultBean.failedResultOfParamWithMsg("授权方式不存在");
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }
            House house = houseOptional.get();

            // 授权前更新未激活智能锁sn值
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();
            String mac = smartLock.getMac();
            String sn = smartLock.getSn();
            if (StringUtils.isBlank(sn)) {
                ResultBean<String> resultBean = smartLockBrandService.getSnByMac(mac, smartLock.getHouseId(),
                        smartLock.getBrandId());
                if (resultBean == null) {
                    return ResultBean.failedResultOfParamWithMsg("智能锁ID为空, 已重新注册, 稍后重试");
                }
                String resultSn = resultBean.getResultData();
                if (StringUtils.isBlank(resultSn)) {
                    return ResultBean.failedResultWithMsg("设备状态异常");
                } else {
                    smartLock.setSn(resultSn);
                    smartLock.setMechineStatus(1);
                    smartLockRepository.save(smartLock);
                }
            }

            /**
             * 验证智能锁，或者 密码， 指纹 身份证 CPU卡  蓝牙 是否冻结
             * true  代表未冻结
             * false  代表已冻结
             * @param lockId 智能锁id
             * @param lockAuthId 用户授权id
             */
            Boolean FreezeBoolean = lockCurrencyService.freezeOrNot(lockId, lockAuthId);
            if (!FreezeBoolean) {
                return ResultBean.failedResultWithMsg("授权失败，智能锁已冻结或授权已冻结！");
            }

            SmartLockFingerprint lockFingerprint = null;
            List<SmartLockFingerprint> fingerprintList = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
            if (fingerprintList.isEmpty()) {// 新增
                lockFingerprint = new SmartLockFingerprint();
                lockFingerprint.setLockAuthId(lockAuthId);
                lockFingerprint.setLockId(lockId);
                lockFingerprint.setCreateTime(new Date());
                lockFingerprint.setLastUpdateTime(lockFingerprint.getCreateTime());

                // 密码序号
                List<SmartLockFingerprint> smartLockPwds = smartLockFingerprintRepository.findByLockId(lockId);
                if (smartLockPwds != null && !smartLockPwds.isEmpty()) {// 已存在序号
                    List<Integer> indexs = smartLockPwds.stream().filter(vo -> vo.getFingerprintIndex() != null)
                            .map(SmartLockFingerprint::getFingerprintIndex).distinct().collect(Collectors.toList());
                    Integer max = Collections.max(indexs);
                    if (max == 200) {
                        // 排除已有序号，取100-200间的最小值
                        List<Integer> list = new ArrayList<>();
                        for (int i = 0, j = 200; i < j; ++i) {
                            list.add(i + 1);
                        }
                        for (Integer i : indexs) {
                            list.remove(i);
                        }
                        Integer min = Collections.min(list);
                        lockFingerprint.setFingerprintIndex(min);
                    } else {
                        lockFingerprint.setFingerprintIndex(max + 1);// 取智能锁指纹序号最大值
                        // +1
                    }
                } else {// 没有序号
                    lockFingerprint.setFingerprintIndex(100);
                }
            } else {// 修改
                lockFingerprint = fingerprintList.get(0);
                lockFingerprint.setLastUpdateTime(new Date());
            }
            // 新增天网互联密码标识
            String identification = lockFingerprint.getIdentification();
            if (StrUtil.isEmpty(identification)) {
                identification = "L" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
            }
            lockFingerprint.setIdentification(identification);
            lockFingerprint.setAuthType(authType);
            lockFingerprint.setAuthTime(new Date());
            lockFingerprint.setStatus(0);// 0待执行
            if (smartLock.getBrandId() == 3L) {
                lockFingerprint.setStatus(1);
            }
            lockFingerprint.setFingerprint(fingerprint);

            // 密码设置方式
            if (authType == 1) {// 永久
                lockFingerprint.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                lockFingerprint.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                lockFingerprint.setLimitDay(
                        DateUtils.daysBetween(lockFingerprint.getStartTime(), lockFingerprint.getEndTime()));
            } else if (authType == 2) {// 时间期限
                lockFingerprint.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                lockFingerprint.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                lockFingerprint.setLimitDay(value);
            } else if (authType == 3) {// 次数
                lockFingerprint.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                lockFingerprint.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                lockFingerprint.setLimitDay(
                        DateUtils.daysBetween(lockFingerprint.getStartTime(), lockFingerprint.getEndTime()));
                lockFingerprint.setAuthorNumber(value);
                lockFingerprint.setTimes(value);
            }

            // 硬件接口
            SmartLockFingerprintVO smartLockVO = new SmartLockFingerprintVO();
            // 新增天网互联密码标识
            smartLockVO.setIdentification(lockFingerprint.getIdentification());
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setFingerprint(fingerprint);
            smartLockVO.setStartTime(DateUtils.format(lockFingerprint.getStartTime(), DateUtils.FORMAT_DATETIME_14));
            smartLockVO.setEndTime(DateUtils.format(lockFingerprint.getEndTime(), DateUtils.FORMAT_DATETIME_14));
            if (smartLock.getBrandId() == 3L) {// 亚略特
                smartLockVO.setStartTime(DateUtils.format(lockFingerprint.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                smartLockVO.setEndTime(DateUtils.format(lockFingerprint.getEndTime(), DateUtils.FORMAT_DATETIME_14));
            }
            smartLockVO.setPwdSeq(lockFingerprint.getFingerprintIndex());
            smartLockVO.setAuthInfoId(lockAuthId);
            smartLockVO.setIndex(lockFingerprint.getFingerprintIndex());
            smartLockVO.setIndexNum(lockFingerprint.getFingerprintIndexNum());
            Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
            if (!optional.isPresent()) {
                log.info("设备品牌信息未找, brandId={}", smartLock.getBrandId());
                return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
            }
            // 采集器型号
            smartLockVO.setFpModel(optional.get().getFingerprintModel());
            if (authType == 1 || authType == 2) {
                smartLockVO.setAuthType(String.valueOf(authType));
            } else if (authType == 3) {
                smartLockVO.setAuthType("5");
                smartLockVO.setTimes(lockFingerprint.getTimes());
            }

            smartLockVO.setIndexNum(lockFingerprint.getFingerprintIndexNum());
            // 熙照
            if (authType == 3) {
                smartLockVO.setTimes(value);
            } else {
                smartLockVO.setTimes(-1);
            }

            // 亚略特
            if (smartLock.getBrandId() == 3L) {
                if (smartLockFingerprintRepository.findByLockAuthId(lockAuthId).isEmpty()) {// 新增
                    lockFingerprint.setfAppUserId(GenerateNiceString.generateNiceString());
                } else {// 修改
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setfAuthorizationID(lockFingerprint.getfAuthorizationId());
                }
                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                yltVO.setfLockMAC(smartLock.getMac());
                yltVO.setfAppUserID(lockFingerprint.getfAppUserId());
                yltVO.setfBeginDate(smartLockVO.getStartTime());
                yltVO.setfEndDate(smartLockVO.getEndTime());
                yltVO.setfOpenByPassword(0);
                yltVO.setfOpenByIDCard(0);
                yltVO.setfOpenByBLE(0);
                yltVO.setfOpenByFinger(1);
                yltVO.setfOpenByICCard(0);
                yltVO.setfFingerFeature(fingerprint.replaceAll("[\\s*\t\n\r]", ""));
                smartLockVO.setYltAuth(yltVO);
            }

            ResultBean<String> stringResultBean = smartLockBrandService.operationFingerprint(smartLockVO,
                    lockFingerprint.getId(), smartLock.getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();
            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authPwd---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService authPwd---> callBack={}", resultData);
                // 生成指纹授权明细
                if (smartLock.getBrandId() == 3L) {// 亚略特
                    lockFingerprint.setfAuthorizationId(resultData);
                }
                smartLockFingerprintRepository.save(lockFingerprint);

                // 更新用户授权明细状态
                updateSmartLockAuthStatus(smartLock.getBrandId(), 4, 1, smartLockAuth);
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                // 发送短信
                if (flag) {
                    String str = smsService.sendTemplateSms(smartLockAuth.getMobile(), smsConfig.getAuthTemplateCode());
                    if (str.equals("success")) {
                        // 如果是承租人授权，更新公租房锁授权状态
                        if (house.getHouseNature() == 1) {
                            if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                                String houseId = smartLockAuth.getHouseId();
                                houseRepository.updateLockStatusById(houseId, 1);
                            }
                        }

                        return ResultBean.successfulResultWithMsg("指令下发成功", null);
                    } else {
                        return ResultBean.failedResultWithMsg("指令下发成功，短信通知失败");
                    }
                } else {
                    return ResultBean.successfulResultWithMsg("指令下发成功", null);
                }
            }

        } catch (Exception e) {
            log.error("LockAppService authFingerprint Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 删除指纹
     *
     * @param lockAuthId 智能锁授权id
     * @param lockId     智能锁id
     * @return
     * @author shun
     * @date 2021年7月7日
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ResultBean<Object> deleteFingerprintAuth(Long lockAuthId, Long lockId) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            List<SmartLockFingerprint> fingerprintList = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
            if (fingerprintList.isEmpty()) {
                return ResultBean.failedResultWithMsg("卡授权明细不存在");
            }
            SmartLockFingerprint lockFingerprint = fingerprintList.get(0);
            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            // 设置天网互联密码标识
            smartLockVO.setIdentification(lockFingerprint.getIdentification());
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setIndex(lockFingerprint.getFingerprintIndex());
            smartLockVO.setAuthInfoId(lockAuthId);
            smartLockVO.setIndexNum(lockFingerprint.getFingerprintIndexNum());
            // 亚略特
            smartLockVO.setfAuthorizationID(lockFingerprint.getfAuthorizationId());

            ResultBean<String> stringResultBean = smartLockBrandService.clearFingerprint(smartLockVO, smartLock.getBrandId(),
                    "fingerprint");
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService deleteFingerprintAuth---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService deleteFingerprintAuth---> callBack={}", resultData);
                // 删除指纹授权
                smartLockFingerprintRepository.delete(lockFingerprint);

                // 更新用户授权明细状态
                updateSmartLockAuthStatus(smartLock.getBrandId(), 4, 2, smartLockAuth);
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                return ResultBean.successfulResultWithMsg("指令下发成功", null);
            }
        } catch (Exception e) {
            log.error("LockAppService deleteFingerprintAuth Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 查看蓝牙授权
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  锁授权id
     * @return
     */
    public ResultBean<Object> findBle(String accessToken, Long lockAuthId) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }

            SmartLockBle smartLockBle = smartLockBleRepository.findByLockAuthId(lockAuthId);

            if (smartLockBle == null) {
                return ResultBean.successfulResultWithMsg("智能锁蓝牙未授权", null);
            } else {
                return ResultBean.successfulResult(smartLockBle);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 授权蓝牙
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  锁授权id
     * @param lockId      锁id
     * @param authType    1永久 2时间期限
     * @param value       日期天数
     * @return
     */
    @Transactional
    public ResultBean<Object> authBle(String accessToken, Long lockAuthId, Long lockId, Integer authType, Integer value) {
        log.info("LockAppService authBle, accessToken={},lockAuthId={},lockId={},authType={},value={}",
                accessToken, lockAuthId, lockId, authType, value);
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("id不存在");
            }
            if (authType == null) {
                return ResultBean.failedResultOfParamWithMsg("授权方式不存在");
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }
            House house = houseOptional.get();

            // 授权前更新未激活智能锁sn值
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            if (smartLock.getBrandId() == 8L || smartLock.getBrandId() == 7L) {
                if (authType == 2) {
                    return ResultBean.failedResultOfParamWithMsg("没有时间期限授权方式");
                }
            }
            String mac = smartLock.getMac();
            String sn = smartLock.getSn();
            if (StringUtils.isBlank(sn)) {
                ResultBean<String> resultBean = smartLockBrandService.getSnByMac(mac, smartLock.getHouseId(),
                        smartLock.getBrandId());
                if (resultBean == null) {
                    return ResultBean.failedResultOfParamWithMsg("智能锁ID为空, 已重新注册, 稍后重试");
                }
                String resultSn = resultBean.getResultData();
                if (StringUtils.isBlank(resultSn)) {
                    return ResultBean.failedResultWithMsg("设备状态异常");
                } else {
                    smartLock.setSn(resultSn);
                    smartLock.setMechineStatus(1);
                    smartLockRepository.save(smartLock);
                }
            }

            /**
             * 验证智能锁，或者 密码， 指纹 身份证 CPU卡  蓝牙 是否冻结
             * true  代表未冻结
             * false  代表已冻结
             * @param lockId 智能锁id
             * @param lockAuthId 用户授权id
             */
            Boolean FreezeBoolean = lockCurrencyService.freezeOrNot(lockId, lockAuthId);
            if (!FreezeBoolean) {
                return ResultBean.failedResultWithMsg("授权失败，智能锁已冻结或授权已冻结！");
            }


            Date date = new Date();
            SmartLockBle smartLockBle = smartLockBleRepository.findByLockAuthId(lockAuthId);
            if (smartLockBle == null) {// 新增
                smartLockBle = new SmartLockBle();
                smartLockBle.setLockId(lockId);
                smartLockBle.setLockAuthId(lockAuthId);
                smartLockBle.setCreateTime(new Date());
            }
            // 新增天网互联密码标识
            String identification = smartLockBle.getIdentification();
            if (smartLock.getBrandId() == 4L) {
                if (StrUtil.isEmpty(identification)) {
                    identification = "L" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
                }
            }
            smartLockBle.setIdentification(identification);
            smartLockBle.setAuthType(authType);
            smartLockBle.setAuthTime(date);
            smartLockBle.setStatus(0);
            if (smartLock.getBrandId() == 3L) {
                smartLockBle.setStatus(1);
            }

            // 卡设置方式
            if (authType == 1) {// 永久
                smartLockBle.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                smartLockBle.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockBle.setLimitDay(DateUtils.daysBetween(smartLockBle.getStartTime(), smartLockBle.getEndTime()));
            } else if (authType == 2) {// 时间期限
                smartLockBle.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                smartLockBle.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockBle.setLimitDay(value);
            }

            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setIdentification(smartLockBle.getIdentification());
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setAuthInfoId(lockAuthId);
            smartLockVO.setStartTime(DateUtils.format(smartLockBle.getStartTime(), DateUtils.FORMAT_14));
            smartLockVO.setEndTime(DateUtils.format(smartLockBle.getEndTime(), DateUtils.FORMAT_14));
            if (smartLock.getBrandId() == 3L) {// 亚略特
                smartLockVO.setStartTime(DateUtils.format(smartLockBle.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                smartLockVO.setEndTime(DateUtils.format(smartLockBle.getEndTime(), DateUtils.FORMAT_DATETIME_14));
            }
            smartLockVO.setDevMac(smartLock.getMac());
            smartLockVO.setTimes(-1);

            // 亚略特
            if (smartLock.getBrandId() == 3L) {
                if (smartLockBleRepository.findByLockAuthId(lockAuthId) == null) {// 新增
                    smartLockBle.setfAppUserId(GenerateNiceString.generateNiceString());
                } else {// 修改
                    smartLockVO.setfAuthorizationID(smartLockBle.getfAuthorizationId());
                }
                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                yltVO.setfLockMAC(smartLock.getMac());
                yltVO.setfAppUserID(smartLockBle.getfAppUserId());
                yltVO.setfBeginDate(smartLockVO.getStartTime());
                yltVO.setfEndDate(smartLockVO.getEndTime());
                yltVO.setfOpenByPassword(0);
                yltVO.setfOpenByBLE(1);
                yltVO.setfOpenByFinger(0);
                yltVO.setfOpenByIDCard(0);
                yltVO.setfOpenByICCard(0);
                smartLockVO.setYltAuth(yltVO);
            }

            ResultBean<String> stringResultBean = smartLockBrandService.operationBle(smartLockVO, smartLockBle, smartLock.getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authBle---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService authBle---> callBack={}", resultData);
                // 生成卡授权明细
                if (smartLock.getBrandId() == 3L) {// 亚略特
                    smartLockBle.setfAuthorizationId(resultData);
                    String blePassword = redisService.getYltFBLEPassword(resultData);
                    smartLockBle.setBlePassword(blePassword);
                }
                smartLockBleRepository.save(smartLockBle);

                // 更新用户授权明细状态
                updateSmartLockAuthStatus(smartLock.getBrandId(), 5, 1, smartLockAuth);
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                // 如果是承租人授权，更新公租房锁授权状态
                if (house.getHouseNature() == 1) {
                    if (smartLockAuth.getMatchUserId().equals(smartLockAuth.getAuthorUserId())) {
                        String houseId = smartLockAuth.getHouseId();
                        houseRepository.updateLockStatusById(houseId, 1);
                    }
                }

                return ResultBean.successfulResultWithMsg("指令下发成功", null);
            }

        } catch (Exception e) {
            log.error("LockAppService authBle Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ResultBean<Object> deleteBle(Long lockAuthId, Long lockId) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            SmartLockBle smartLockBle = smartLockBleRepository.findByLockAuthId(lockAuthId);
            if (smartLockBle == null) {
                return ResultBean.failedResultWithMsg("蓝牙授权明细不存在");
            }

            // 硬件接口
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setAuthInfoId(lockAuthId);
            // 亚略特
            smartLockVO.setfAuthorizationID(smartLockBle.getfAuthorizationId());

            ResultBean<String> stringResultBean = smartLockBrandService.clearBle(smartLockVO, smartLock.getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService deleteBle---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService deleteBle---> callBack={}", resultData);
                // 删除指纹授权
                smartLockBleRepository.delete(smartLockBle);

                // 更新用户授权明细状态
                updateSmartLockAuthStatus(smartLock.getBrandId(), 5, 2, smartLockAuth);
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                return ResultBean.successfulResultWithMsg("指令下发成功", null);
            }
        } catch (Exception e) {
            log.error("LockAppService deleteBle Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    @Transactional
    public ResultBean<Object> frozenOrUnfrozenAuth(String accessToken, Long lockId, Integer type, String reason) {
        try {
            log.info("frozenOrUnfrozenAuth, lockId={}, type={}, reason={}", lockId, type, reason);
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("操作类型为空");
            }
            if (type == 1 && StringUtils.isBlank(reason)) {
                return ResultBean.failedResultOfParamWithMsg("冻结原因为空");
            }

            // 获取缓存
            Object redis = redisTemplate.opsForValue().get("lock_id:" + lockId);
            if (redis != null) {
                return ResultBean.failedResultWithMsg("检测有操作记录，请稍后重试");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();
            Date date = new Date();

            boolean adopt = true;
            // 只有类型为解冻时，才验证是否有权限解冻
            if (type == 0) {
                // 获得该锁的最后一次冻结记录 HouseLockFrozenLog
                HouseLockFrozenLog lock = houseLockFrozenLogRepository.findByLockIdAndType(lockId, 1);
                if (null != lock) {
                    Integer operationState = lock.getOperationState();
                    if (ObjectUtil.equals(operationState, 2)) {
                        return ResultBean.failedResultWithMsg("系统自动冻结，您无权解冻");
                    }
                    // 1、操作冻结的用户与解冻用户，是否属于同一个人 ，如果不属于则判断操作冻结的用户与解冻的用户，属于同机构且在同一个部门
                    if (!lock.getOperationId().equals(userId)) {
                        // 冻结权限
                        String sql1 = " SELECT r.dep_id as depId FROM saas_user u \n" +
                                " LEFT JOIN saas_user_department_ref r ON u.id = r.user_id\n" +
                                " WHERE u.id = ? OR u.id IN(SELECT enterprise_user_id FROM saas_app_user WHERE id = ? OR enterprise_user_id = ?)";
                        List<String> args1 = new ArrayList<>();
                        args1.add(lock.getOperationId());// 操作冻结的用户Id
                        args1.add(lock.getOperationId());// 操作冻结的用户Id
                        args1.add(lock.getOperationId());// 操作冻结的用户Id
                        List<UserDepartmentRef> departmentRef1 = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(UserDepartmentRef.class), args1.toArray());
                        List<Long> depId1 = departmentRef1.stream().distinct().map(x -> x.getDepId()).collect(Collectors.toList());


                        String sql2 = " SELECT r.dep_id as depId  FROM saas_user u \n" +
                                " LEFT JOIN saas_user_department_ref r ON u.id = r.user_id\n" +
                                " WHERE u.id = ? OR u.id IN(SELECT enterprise_user_id FROM saas_app_user WHERE id = ? OR enterprise_user_id = ?)";
                        List<String> args2 = new ArrayList<>();
                        args2.add(tokenRedisVo.getId());// 当前登录人的id
                        args2.add(tokenRedisVo.getId());// 当前登录人的id
                        args2.add(tokenRedisVo.getId());// 当前登录人的id
                        List<UserDepartmentRef> departmentRef2 = jdbcTemplate.query(sql2, new BeanPropertyRowMapper<>(UserDepartmentRef.class), args2.toArray());
                        List<Long> depId2 = departmentRef2.stream().distinct().map(x -> x.getDepId()).collect(Collectors.toList());

                        if (depId1 != null && depId1.size() > 0 && depId2 != null && depId2.size() > 0) {
                            adopt = false;
                            for (Long aLong : depId1) {
                                if (depId2.contains(aLong)) {
                                    adopt = true;
                                    break;
                                }
                            }

                        } else {
                            adopt = false;
                        }
                    }
                }

            }


            if (adopt) {
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 0);
                for (SmartLockAuth smartLockAuth : auths) {
                    Long lockAuthId = smartLockAuth.getId();
                    SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
                    List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
                    List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
                    SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
                    SmartLockFace face = smartLockFaceRepository.findByLockAuthId(lockAuthId);
                    if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null || face != null) {
                        // 新增冻结记录
                        String houseId = smartLock.getHouseId();
                        // String matchUserName = smartLock.getMatchUserName();
                        String communityName = smartLock.getCommunityName();
                        String buildName = smartLock.getBuildName();
                        String unitName = smartLock.getUnitName();
                        String roomNumber = smartLock.getRoomNumber();

                        LockFrozen lockFrozen = new LockFrozen();
                        lockFrozen.setType(type);
                        lockFrozen.setLockId(lockId);
                        lockFrozen.setLockAuditId(lockAuthId);
                        lockFrozen.setHouseId(houseId);
                        lockFrozen.setMatchUserName(smartLockAuth.getUserName());
                        lockFrozen.setCommunityName(communityName);
                        lockFrozen.setBuildName(buildName);
                        lockFrozen.setUnitName(unitName);
                        lockFrozen.setRoomNumber(roomNumber);
                        lockFrozen.setOperationId(userId);
                        lockFrozen.setOperationTime(date);
                        if (StringUtils.isNotBlank(reason)) {
                            lockFrozen.setReason(reason);
                        }
                        LockFrozen frozenSave = lockFrozenRepository.save(lockFrozen);

                        // 冻结密码
                        if (pwd != null) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            // 新增天网互联密码标识
                            smartLockVO.setIdentification(pwd.getIdentification());
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setPwdType(pwd.getType());
                            smartLockVO.setPassword(pwd.getPassword());
                            smartLockVO.setIndex(pwd.getPwdIndex());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setReturnPwdId(pwd.getReturnPwdId());
                            Integer authType = pwd.getAuthType();
                            if (authType == 1 || authType == 2) {
                                smartLockVO.setAuthType(LockAuthTypeEnum.NORMAL_PASS.getValue());
                            } else if (authType == 3) {
                                smartLockVO.setAuthType(LockAuthTypeEnum.TIMES_PASS.getValue());
                                smartLockVO.setTimes(pwd.getTimes());
                            }
                            smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                            smartLockVO.setLockFrozenId(frozenSave.getId());
                            smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                if (type == 1) {
                                    smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                                } else {
                                    YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                    yltVO.setfLockMAC(smartLock.getMac());
                                    yltVO.setfAppUserID(pwd.getfAppUserId());
                                    yltVO.setfBeginDate(DateUtils.format(pwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfEndDate(DateUtils.format(pwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfOpenByPassword(1);
                                    yltVO.setfOpenByIDCard(0);
                                    yltVO.setfOpenByBLE(0);
                                    yltVO.setfOpenByFinger(0);
                                    yltVO.setfOpenByICCard(0);
                                    yltVO.setfOpenPassword(pwd.getPassword());
                                    smartLockVO.setYltAuth(yltVO);
                                }
                            }

                            ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreeze(smartLockVO,
                                    smartLock.getBrandId(), XzLockOperatorTypeEnum.PWD.getValue());
                            String resultData = stringResultBean.getResultData();
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                // 失败，删除冻结记录
                                lockFrozenRepository.deleteById(frozenSave.getId());
                                return ResultBean.failedResultWithCodeAndMsg(code, msg);
                            } else {

                                if (smartLock.getBrandId() == 6L && type == 0) {
                                    Long id = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
                                    if (id != null) {
                                        pwd.setReturnPwdId(id);
                                    }
                                }
                                if (smartLock.getBrandId() == 5L && type == 0) {
                                    pwd.setIdentification(resultData);
                                }
                                if (smartLock.getBrandId() == 8L && type == 0) {
                                    String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                                    pwd.setIdentification(phoneNo);
                                    String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                                    pwd.setfAuthorizationId(keyId);
                                }
                                // 冻结后默认待执行
                                pwd.setStatus(0);
                                smartLockPwdRepository.save(pwd);
                                // 亚略特
                                // if (smartLock.getBrandId() == 3L) {
                                yltUpdateStatus(pwd, null, null, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                //}
                            }
                        }

                        // 冻结卡
                        if (!cards.isEmpty()) {
                            for (SmartLockCard card : cards) {
                                SmartLockVO smartLockVO = new SmartLockVO();
                                // 新增天网互联密码标识
                                smartLockVO.setIdentification(card.getIdentification());
                                smartLockVO.setCardType(card.getType());
                                smartLockVO.setSn(smartLock.getSn());
                                smartLockVO.setIndex(card.getCardIndex());
                                smartLockVO.setAuthInfoId(lockAuthId);
                                smartLockVO.setCardType(card.getType());
                                smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                                smartLockVO.setLockFrozenId(frozenSave.getId());
                                smartLockVO.setIndexNum(card.getCardIndexNum());
                                smartLockVO.setReturnCardId(card.getReturnCardId());
                                // 亚略特
                                if (smartLock.getBrandId() == 3L) {
                                    if (type == 1) {
                                        smartLockVO.setfAuthorizationID(card.getfAuthorizationId());
                                    } else {
                                        YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                        yltVO.setfLockMAC(smartLock.getMac());
                                        yltVO.setfAppUserID(card.getfAppUserId());
                                        yltVO.setfBeginDate(DateUtils.format(card.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfEndDate(DateUtils.format(card.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfOpenByPassword(0);
                                        yltVO.setfOpenByBLE(0);
                                        yltVO.setfOpenByFinger(0);
                                        if (card.getType() == 1) {
                                            yltVO.setfOpenByIDCard(1);
                                            yltVO.setfOpenByICCard(0);
                                        } else {
                                            yltVO.setfOpenByIDCard(0);
                                            yltVO.setfOpenByICCard(1);
                                        }
                                        yltVO.setfIDCardID(card.getCardId());
                                        yltVO.setfIDCardNumber(card.getCardNumber());
                                        smartLockVO.setYltAuth(yltVO);
                                    }
                                }

                                ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeCard(
                                        smartLockVO, smartLock.getBrandId(), XzLockOperatorTypeEnum.CARD.getValue());
                                String resultData = stringResultBean.getResultData();
                                String msg = stringResultBean.getMsg();
                                String code = stringResultBean.getCode();
                                if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                    log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                    // 失败，删除冻结记录
                                    lockFrozenRepository.deleteById(frozenSave.getId());
                                    return ResultBean.failedResultWithCodeAndMsg(code, msg);
                                } else {

                                    if (smartLock.getBrandId() == 6L && type == 0) {
                                        Long id = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
                                        if (id != null) {
                                            pwd.setReturnPwdId(id);
                                        }
                                    }
                                    if (smartLock.getBrandId() == 8L && type == 0) {
                                        String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                                        card.setIdentification(phoneNo);
                                        String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                                        card.setfAuthorizationId(keyId);
                                    } else {
                                        card.setIdentification(resultData);
                                    }
                                    // 冻结后默认待执行
                                    card.setStatus(0);
                                    smartLockCardRepository.save(card);
                                    // 亚略特
                                    // if (smartLock.getBrandId() == 3L) {
                                    yltUpdateStatus(null, card, null, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                    //}
                                }
                            }
                        }

                        // 指纹锁
                        if (!fingerprint.isEmpty()) {
                            Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                            if (optional.isPresent()) {
                                SmartLockBrand brand = optional.get();
                                // 品牌支持指纹锁
                                if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                                    for (SmartLockFingerprint fg : fingerprint) {
                                        SmartLockVO smartLockVO = new SmartLockVO();
                                        // 新增天网互联密码标识
                                        smartLockVO.setIdentification(fg.getIdentification());
                                        smartLockVO.setAuthType(String.valueOf(fg.getAuthType()));
                                        smartLockVO.setSn(smartLock.getSn());
                                        smartLockVO.setFingerprint(fg.getFingerprint());
                                        smartLockVO.setIndex(fg.getFingerprintIndex());
                                        smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                        smartLockVO.setAuthInfoId(lockAuthId);
                                        smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                                        smartLockVO.setLockFrozenId(frozenSave.getId());
                                        // 亚略特
                                        if (smartLock.getBrandId() == 3L) {
                                            if (type == 1) {
                                                smartLockVO.setfAuthorizationID(fg.getfAuthorizationId());
                                            } else {
                                                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                                yltVO.setfLockMAC(smartLock.getMac());
                                                yltVO.setfAppUserID(fg.getfAppUserId());
                                                yltVO.setfBeginDate(DateUtils.format(fg.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                                yltVO.setfEndDate(DateUtils.format(fg.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                                yltVO.setfOpenByPassword(0);
                                                yltVO.setfOpenByIDCard(0);
                                                yltVO.setfOpenByBLE(0);
                                                yltVO.setfOpenByFinger(1);
                                                yltVO.setfOpenByICCard(0);
                                                yltVO.setfFingerFeature(fg.getFingerprint());
                                                smartLockVO.setYltAuth(yltVO);
                                            }
                                        }

                                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFingerprint(smartLockVO, smartLock.getBrandId(),
                                                XzLockOperatorTypeEnum.FINGERPRINT.getValue());
                                        String msg = stringResultBean.getMsg();
                                        String code = stringResultBean.getCode();
                                        if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                                            log.error("LockAppService deleteUser---> " + msg);
                                            // 失败，删除冻结记录
                                            lockFrozenRepository.deleteById(frozenSave.getId());
                                            return ResultBean.failedResultWithCodeAndMsg(code, msg);
                                        } else {
                                            // 冻结后默认待执行
                                            fg.setStatus(0);
                                            smartLockFingerprintRepository.save(fg);
                                            // 亚略特
                                            // if (smartLock.getBrandId() == 3L) {
                                            yltUpdateStatus(null, null, fg, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                            //}
                                        }
                                    }
                                }
                            }
                        }

                        // 蓝牙
                        if (ble != null) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            // 新增天网互联密码标识
                            smartLockVO.setIdentification(ble.getIdentification());
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                            smartLockVO.setLockFrozenId(frozenSave.getId());
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                if (type == 1) {
                                    smartLockVO.setfAuthorizationID(ble.getfAuthorizationId());
                                } else {
                                    YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                    yltVO.setfLockMAC(smartLock.getMac());
                                    yltVO.setfAppUserID(ble.getfAppUserId());
                                    yltVO.setfBeginDate(DateUtils.format(ble.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfEndDate(DateUtils.format(ble.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfOpenByPassword(0);
                                    yltVO.setfOpenByIDCard(0);
                                    yltVO.setfOpenByBLE(1);
                                    yltVO.setfOpenByFinger(0);
                                    yltVO.setfOpenByICCard(0);
                                    smartLockVO.setYltAuth(yltVO);
                                }
                            }

                            ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeBle(smartLockVO, smartLock.getBrandId());
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                // 失败，删除冻结记录
                                lockFrozenRepository.deleteById(frozenSave.getId());
                                return ResultBean.failedResultWithCodeAndMsg(code, msg);
                            } else {
                                // 冻结后默认待执行
                                ble.setStatus(0);
                                smartLockBleRepository.save(ble);
                                // 亚略特
                                // if (smartLock.getBrandId() == 3L) {
                                yltUpdateStatus(null, null, null, ble, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                //}
                            }
                        }

                        // 人脸
                        if (face != null) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                            smartLockVO.setLockFrozenId(frozenSave.getId());

                            face.setSn(smartLock.getSn());
                            ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFace(smartLockVO, face, smartLock.getBrandId());
                            String resultData = stringResultBean.getResultData();
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                // 失败，删除冻结记录
                                lockFrozenRepository.deleteById(frozenSave.getId());
                                return ResultBean.failedResultWithCodeAndMsg(code, msg);
                            } else {
                                if (StrUtil.isNotEmpty(resultData)) {
                                    if (smartLock.getBrandId() == 8L) {
                                        String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                                        face.setIdentification(phoneNo);
                                        String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                                        face.setKeyId(keyId);
                                    } else {
                                        face.setIdentification(resultData);
                                        face.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
                                    }
                                }
                                // 冻结后默认待执行
                                face.setStatus(0);
                                smartLockFaceRepository.save(face);
                                // 亚略特
                                // if (smartLock.getBrandId() == 3L) {
                                yltUpdateStatus(null, null, null, null, face, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                //}
                            }
                        }


                    }
                    //  写入冻结日志表
                    HouseLockFrozenLog houseLockFrozenLog = new HouseLockFrozenLog();
                    houseLockFrozenLog.setType(type);// 操作类型: 0:解冻 1:冻结
                    houseLockFrozenLog.setLockId(lockId);// 智能锁绑定id
                    houseLockFrozenLog.setHouseId(smartLock.getHouseId()); // 公租房id
                    houseLockFrozenLog.setLockAuditId(lockAuthId); // 授权信息id
                    houseLockFrozenLog.setOperationId(userId); // 冻结操作人
                    houseLockFrozenLog.setOperationTime(new Date()); // 操作时间
                    houseLockFrozenLog.setOperationState(1); // 操作时间
                    houseLockFrozenLogRepository.save(houseLockFrozenLog);

                    /**
                     * 产生智能锁冻结/解冻待办事项
                     */
                    addBacklogItem(smartLockAuth.getMobile(), reason, type, smartLock.getHouseId(), smartLockAuth.getAuthorUserId(), userId, enterpriseId);

                }

                /**
                 * 产生智能锁冻结/解冻待办事项 企业端
                 */
                addBacklogItemEnterprise(auths.get(0).getMobile(), reason, type, smartLock.getHouseId(), auths.get(0).getAuthorUserId(), userId, enterpriseId);

                // 更新冻结原因
                if (type == 1) {
                    smartLock.setReason(reason);
                } else {
                    smartLock.setReason(null);
                }

                //  写入冻结日志表
                HouseLockFrozenLog houseLockFrozenLog = new HouseLockFrozenLog();
                houseLockFrozenLog.setType(type);// 操作类型: 0:解冻 1:冻结
                houseLockFrozenLog.setLockId(lockId);// 智能锁绑定id
                houseLockFrozenLog.setHouseId(smartLock.getHouseId()); // 公租房id
                houseLockFrozenLog.setOperationId(userId); // 冻结操作人
                houseLockFrozenLog.setOperationTime(new Date()); // 操作时间
                houseLockFrozenLogRepository.save(houseLockFrozenLog);


                // 更新公租房锁授权状态
                String houseId = smartLock.getHouseId();
                if (type == 1) {
                    houseRepository.updateLockStatusById(houseId, 4);
                } else if (type == 0) {
                    houseRepository.updateLockStatusById(houseId, 1);
                }

                // 更新亚略特智能锁状态
                yltUpdateLockStatus(smartLock, type);

                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                // 操作成功设置缓存，防止重复操作
                redisTemplate.opsForValue().set("lock_id:" + lockId, "", 1, TimeUnit.MINUTES);
                return ResultBean.successfulResult(null);
            } else {
                log.info("frozenOrUnfrozenAuth:您没有解冻/冻结的权限 ");
                return ResultBean.failedResultWithMsg("您没有解冻/冻结的权限");
            }
        } catch (Exception e) {
            log.error("LockAppService frozenOrUnfrozenAuth Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 单用户冻结/解冻
     *
     * @param accessToken
     * @param lockId
     * @param type        类型：0:解冻 1:冻结
     * @param reason      冻结备注
     * @return
     * @author shun
     * @date 2021年7月7日
     */
    public ResultBean<Object> personFrozenOrUnfrozenAuth(String accessToken, Long lockId, Long lockAuthId, Integer type,
                                                         String reason) {
        try {
            log.info("personFrozenOrUnfrozenAuth, lockId={}, lockAuthId={}, type={}, reason={}", lockId, lockAuthId, type, reason);
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁ID为空");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("操作类型为空");
            }
            if (type == 1 && StringUtils.isBlank(reason)) {
                return ResultBean.failedResultOfParamWithMsg("冻结原因为空");
            }
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("授权ID为空");
            }

            // 获取缓存
            Object redis = redisTemplate.opsForValue().get("lock_p_id:" + lockId + lockAuthId);
            if (redis != null) {
                return ResultBean.failedResultWithMsg("检测有操作记录，请稍后重试");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();
            Date date = new Date();

            Optional<SmartLockAuth> auths = smartLockAuthRepository.findById(lockAuthId);
            if (!auths.isPresent()) {
                return ResultBean.failedResultWithMsg("授权信息有误");
            }
            SmartLockAuth smartLockAuth = auths.get();

            Boolean adopt = true;
            // 只有类型为解冻时，才验证是否有权限解冻
            if (type == 0) {
                // 获得该锁的最后一次冻结记录
                HouseLockFrozenLog lock = houseLockFrozenLogRepository.findByLockIdAndLockAuditIdAndType(lockId, lockAuthId, 1);
                if (null != lock) {
                    Integer operationState = lock.getOperationState();
                    if (ObjectUtil.equals(operationState, 2)) {
                        return ResultBean.failedResultWithMsg("系统自动冻结，您无权解冻");
                    }
                    // 1、操作冻结的用户与解冻用户，是否属于同一个人 ，如果不属于则判断操作冻结的用户与解冻的用户，属于同机构且在同一个部门
                    if (!lock.getOperationId().equals(userId)) {
                        // 冻结权限
                        String sql1 = " SELECT r.dep_id as depId FROM saas_user u \n" +
                                " LEFT JOIN saas_user_department_ref r ON u.id = r.user_id\n" +
                                " WHERE u.id = ? OR u.id IN(SELECT enterprise_user_id FROM saas_app_user WHERE id = ? OR enterprise_user_id = ?)";
                        List<String> args1 = new ArrayList<>();
                        args1.add(lock.getOperationId());// 操作冻结的用户Id
                        args1.add(lock.getOperationId());// 操作冻结的用户Id
                        args1.add(lock.getOperationId());// 操作冻结的用户Id
                        List<UserDepartmentRef> departmentRef1 = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(UserDepartmentRef.class), args1.toArray());
                        List<Long> depId1 = departmentRef1.stream().distinct().map(x -> x.getDepId()).collect(Collectors.toList());


                        String sql2 = " SELECT r.dep_id as depId  FROM saas_user u \n" +
                                " LEFT JOIN saas_user_department_ref r ON u.id = r.user_id\n" +
                                " WHERE u.id = ? OR u.id IN(SELECT enterprise_user_id FROM saas_app_user WHERE id = ? OR enterprise_user_id = ?)";
                        List<String> args2 = new ArrayList<>();
                        args2.add(tokenRedisVo.getId());// 当前登录人的id
                        args2.add(tokenRedisVo.getId());// 当前登录人的id
                        args2.add(tokenRedisVo.getId());// 当前登录人的id
                        List<UserDepartmentRef> departmentRef2 = jdbcTemplate.query(sql2, new BeanPropertyRowMapper<>(UserDepartmentRef.class), args2.toArray());
                        List<Long> depId2 = departmentRef2.stream().distinct().map(x -> x.getDepId()).collect(Collectors.toList());

                        if (depId1 != null && depId1.size() > 0 && depId2 != null && depId2.size() > 0) {
                            adopt = false;
                            for (Long aLong : depId1) {
                                if (depId2.contains(aLong)) {
                                    adopt = true;
                                    break;
                                }
                            }

                        } else {
                            adopt = false;
                        }

                    }
                }

            }

            if (adopt) {
                // 单用户授权冻结, 一次冻结密码、身份证、CPU、指纹
                SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
                List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
                List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
                SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
                SmartLockFace face = smartLockFaceRepository.findByLockAuthId(lockAuthId);
                if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null || face != null) {
                    // 新增冻结记录
                    String houseId = smartLock.getHouseId();
                    // String matchUserName = smartLock.getMatchUserName();
                    String communityName = smartLock.getCommunityName();
                    String buildName = smartLock.getBuildName();
                    String unitName = smartLock.getUnitName();
                    String roomNumber = smartLock.getRoomNumber();

                    LockFrozen lockFrozen = new LockFrozen();
                    lockFrozen.setType(type);
                    lockFrozen.setLockId(lockId);
                    lockFrozen.setLockAuditId(lockAuthId);
                    lockFrozen.setHouseId(houseId);
                    lockFrozen.setMatchUserName(smartLockAuth.getUserName());
                    lockFrozen.setCommunityName(communityName);
                    lockFrozen.setBuildName(buildName);
                    lockFrozen.setUnitName(unitName);
                    lockFrozen.setRoomNumber(roomNumber);
                    lockFrozen.setOperationId(userId);
                    lockFrozen.setOperationTime(date);
                    if (StringUtils.isNotBlank(reason)) {
                        lockFrozen.setReason(reason);
                    }
                    LockFrozen frozenSave = lockFrozenRepository.save(lockFrozen);

                    // 冻结密码
                    if (pwd != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setIndex(pwd.getPwdIndex());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setPassword(pwd.getPassword());
                        Integer authType = pwd.getAuthType();
                        if (authType == 1 || authType == 2) {
                            smartLockVO.setAuthType(LockAuthTypeEnum.NORMAL_PASS.getValue());
                        } else if (authType == 3) {
                            smartLockVO.setAuthType(LockAuthTypeEnum.TIMES_PASS.getValue());
                            smartLockVO.setTimes(pwd.getTimes());
                        }
                        smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());
                        smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                        smartLockVO.setIdentification(pwd.getIdentification());
                        smartLockVO.setPwdType(pwd.getType());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            if (type == 1) {
                                smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                            } else {
                                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                yltVO.setfLockMAC(smartLock.getMac());
                                yltVO.setfAppUserID(pwd.getfAppUserId());
                                yltVO.setfBeginDate(DateUtils.format(pwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfEndDate(DateUtils.format(pwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfOpenByPassword(1);
                                yltVO.setfOpenByIDCard(0);
                                yltVO.setfOpenByBLE(0);
                                yltVO.setfOpenByFinger(0);
                                yltVO.setfOpenByICCard(0);
                                yltVO.setfOpenPassword(pwd.getPassword());
                                smartLockVO.setYltAuth(yltVO);
                            }
                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreeze(smartLockVO,
                                smartLock.getBrandId(), XzLockOperatorTypeEnum.PWD.getValue());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                        } else {
                            // 冻结后默认待执行
                            pwd.setStatus(0);
                            smartLockPwdRepository.save(pwd);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            yltUpdateStatus(pwd, null, null, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                            //}

                            if (type == 1) {
                                smartLockAuth.setPwdStatus(2);
                            } else if (type == 0) {
                                smartLockAuth.setPwdStatus(1);
                            }
                        }
                    }

                    // 冻结卡
                    if (!cards.isEmpty()) {
                        for (SmartLockCard card : cards) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(card.getCardIndex());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setCardType(card.getType());
                            smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                            smartLockVO.setLockFrozenId(frozenSave.getId());
                            smartLockVO.setIndexNum(card.getCardIndexNum());
                            smartLockVO.setIdentification(card.getIdentification());
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                if (type == 1) {
                                    smartLockVO.setfAuthorizationID(card.getfAuthorizationId());
                                } else {
                                    YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                    yltVO.setfLockMAC(smartLock.getMac());
                                    yltVO.setfAppUserID(card.getfAppUserId());
                                    yltVO.setfBeginDate(DateUtils.format(card.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfEndDate(DateUtils.format(card.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfOpenByPassword(0);
                                    yltVO.setfOpenByBLE(0);
                                    yltVO.setfOpenByFinger(0);
                                    if (card.getType() == 1) {
                                        yltVO.setfOpenByIDCard(1);
                                        yltVO.setfOpenByICCard(0);
                                    } else {
                                        yltVO.setfOpenByIDCard(0);
                                        yltVO.setfOpenByICCard(1);
                                    }
                                    yltVO.setfIDCardID(card.getCardId());
                                    yltVO.setfIDCardNumber(card.getCardNumber());
                                    smartLockVO.setYltAuth(yltVO);
                                }
                            }

                            ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeCard(smartLockVO,
                                    smartLock.getBrandId(), XzLockOperatorTypeEnum.CARD.getValue());
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                // 失败，删除冻结记录
                                lockFrozenRepository.deleteById(frozenSave.getId());
                            } else {
                                // 冻结后默认待执行
                                card.setStatus(0);
                                smartLockCardRepository.save(card);
                                // 亚略特
                                // if (smartLock.getBrandId() == 3L) {
                                yltUpdateStatus(null, card, null, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                //}

                                if (type == 1) {
                                    smartLockAuth.setCardStatus(2);
                                } else if (type == 0) {
                                    smartLockAuth.setCardStatus(1);
                                }
                            }
                        }
                    }

                    // 指纹锁
                    if (!fingerprint.isEmpty()) {
                        Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                        if (optional.isPresent()) {
                            SmartLockBrand brand = optional.get();
                            // 品牌支持指纹锁
                            if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                                for (SmartLockFingerprint fg : fingerprint) {
                                    SmartLockVO smartLockVO = new SmartLockVO();
                                    smartLockVO.setSn(smartLock.getSn());
                                    smartLockVO.setIndex(fg.getFingerprintIndex());
                                    smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                    smartLockVO.setAuthInfoId(lockAuthId);
                                    smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                                    smartLockVO.setLockFrozenId(frozenSave.getId());
                                    smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                    // 亚略特
                                    if (smartLock.getBrandId() == 3L) {
                                        if (type == 1) {
                                            smartLockVO.setfAuthorizationID(fg.getfAuthorizationId());
                                        } else {
                                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                            yltVO.setfLockMAC(smartLock.getMac());
                                            yltVO.setfAppUserID(fg.getfAppUserId());
                                            yltVO.setfBeginDate(DateUtils.format(fg.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                            yltVO.setfEndDate(DateUtils.format(fg.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                            yltVO.setfOpenByPassword(0);
                                            yltVO.setfOpenByIDCard(0);
                                            yltVO.setfOpenByBLE(0);
                                            yltVO.setfOpenByFinger(1);
                                            yltVO.setfOpenByICCard(0);
                                            yltVO.setfFingerFeature(fg.getFingerprint());
                                            smartLockVO.setYltAuth(yltVO);
                                        }
                                    }

                                    ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFingerprint(
                                            smartLockVO, smartLock.getBrandId(), XzLockOperatorTypeEnum.FINGERPRINT.getValue());
                                    String msg = stringResultBean.getMsg();
                                    String code = stringResultBean.getCode();
                                    if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                                        log.error("LockAppService deleteUser---> " + msg);
                                        // 失败，删除冻结记录
                                        lockFrozenRepository.deleteById(frozenSave.getId());
                                    } else {
                                        // 冻结后默认待执行
                                        fg.setStatus(0);
                                        smartLockFingerprintRepository.save(fg);
                                        // 亚略特
                                        // if (smartLock.getBrandId() == 3L) {
                                        yltUpdateStatus(null, null, fg, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                        //}

                                        if (type == 1) {
                                            smartLockAuth.setFingerprintStatus(2);
                                        } else if (type == 0) {
                                            smartLockAuth.setFingerprintStatus(1);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // 蓝牙
                    if (ble != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setIdentification(ble.getIdentification());
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            if (type == 1) {
                                smartLockVO.setfAuthorizationID(ble.getfAuthorizationId());
                            } else {
                                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                yltVO.setfLockMAC(smartLock.getMac());
                                yltVO.setfAppUserID(ble.getfAppUserId());
                                yltVO.setfBeginDate(DateUtils.format(ble.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfEndDate(DateUtils.format(ble.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfOpenByPassword(0);
                                yltVO.setfOpenByIDCard(0);
                                yltVO.setfOpenByBLE(1);
                                yltVO.setfOpenByFinger(0);
                                yltVO.setfOpenByICCard(0);
                                smartLockVO.setYltAuth(yltVO);
                            }
                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeBle(smartLockVO, smartLock.getBrandId());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                            return ResultBean.failedResultWithCodeAndMsg(code, msg);
                        } else {
                            // 冻结后默认待执行
                            ble.setStatus(0);
                            smartLockBleRepository.save(ble);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            yltUpdateStatus(null, null, null, ble, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                            //}

                            if (type == 1) {
                                smartLockAuth.setBleStatus(2);
                            } else if (type == 0) {
                                smartLockAuth.setBleStatus(1);
                            }
                        }
                    }

                    if (face != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());

                        face.setSn(smartLock.getSn());
                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFace(smartLockVO, face, smartLock.getBrandId());
                        String resultData = stringResultBean.getResultData();
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                            return ResultBean.failedResultWithCodeAndMsg(code, msg);
                        } else {
                            if (StrUtil.isNotEmpty(resultData)) {
                                if (smartLock.getBrandId() == 8L) {
                                    String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                                    face.setIdentification(phoneNo);
                                    String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                                    face.setKeyId(keyId);
                                } else {
                                    face.setIdentification(resultData);
                                    face.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
                                }
                            }
                            // 冻结后默认待执行
                            face.setStatus(0);
                            smartLockFaceRepository.save(face);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            yltUpdateStatus(null, null, null, null, face, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                            //}

                            if (type == 1) {
                                smartLockAuth.setFaceStatus(2);
                            } else if (type == 0) {
                                smartLockAuth.setFaceStatus(1);
                            }
                        }
                    }
                }


                // 更新冻结原因
                if (type == 1) {
                    smartLock.setReason(reason);
                } else {
                    smartLock.setReason(null);
                }
                //  写入冻结日志表
                HouseLockFrozenLog houseLockFrozenLog = new HouseLockFrozenLog();
                houseLockFrozenLog.setType(type);// 操作类型: 0:解冻 1:冻结
                houseLockFrozenLog.setLockId(lockId);// 智能锁绑定id
                houseLockFrozenLog.setHouseId(smartLock.getHouseId()); // 公租房id
                houseLockFrozenLog.setLockAuditId(lockAuthId); // 授权信息id
                houseLockFrozenLog.setOperationId(userId); // 冻结操作人
                houseLockFrozenLog.setOperationTime(new Date()); // 操作时间
                houseLockFrozenLogRepository.save(houseLockFrozenLog);


                /**
                 * 产生智能锁冻结/解冻待办事项
                 */
                addBacklogItem(smartLockAuth.getMobile(), reason, type, smartLock.getHouseId(), smartLockAuth.getAuthorUserId(), userId, enterpriseId);
                // 更新亚略特智能锁状态
                yltUpdateLockStatus(smartLock, type);

                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                // 操作成功设置缓存，防止重复操作
                redisTemplate.opsForValue().set("lock_p_id:" + lockId + lockAuthId, "", 1, TimeUnit.MINUTES);

                smartLockAuthRepository.save(smartLockAuth);

                return ResultBean.successfulResult(null);
            } else {
                log.info("personFrozenOrUnfrozenAuth:您没有解冻/冻结的权限 ");
                return ResultBean.failedResultWithMsg("您没有解冻/冻结的权限");
            }
        } catch (Exception e) {
            log.error("LockAppService frozenOrUnfrozenAuth Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 授权全部删除(解绑)
     *
     * @param accessToken 权限鉴定
     * @param lockId      锁id
     * @return
     * @author shun
     * @date 2021年7月7日
     */
    @Transactional
    public ResultBean<Object> delAllAuth(String accessToken, Long lockId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            if (lockId == null) {
                log.info("授权全部删除, 智能锁id为空, lockId={}", lockId);
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            // 获取缓存
            Object redis = redisTemplate.opsForValue().get("lock_del_id:" + lockId);
            if (redis != null) {
                log.info("授权全部删除, 检测有操作记录, lockId={}", lockId);
                return ResultBean.failedResultWithMsg("检测有操作记录，请稍后重试");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                log.info("授权全部删除, 智能锁不存在, lockId={}", lockId);
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }

            SmartLock smartLock = lockOptional.get();
            List<SmartLockAuth> auths = smartLockAuthRepository.findByLockId(lockId);
            log.info("LockAppService delAllAuth, auths={}", JSON.toJSONString(auths));

            for (SmartLockAuth smartLockAuth : auths) {
                Long lockAuthId = smartLockAuth.getId();
                redisService.deleteAuthTemporaryPwd(smartLockAuth.getMobile(), smartLockAuth.getHouseId());
                SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
                List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
                List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
                SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
                SmartLockFace face = smartLockFaceRepository.findByLockAuthId(lockAuthId);
                if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null || face != null) {
                    // 删除密码授权
                    if (pwd != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setIndex(pwd.getPwdIndex());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                        }
                        smartLockVO.setIdentification(pwd.getIdentification());

                        ResultBean<String> stringResultBean = smartLockBrandService.clearPassword(smartLockVO,
                                smartLock.getBrandId(), "code", lockId);
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, vo={}", code, msg,
                                JSON.toJSONString(smartLockVO));
                    }

                    // 删除卡授权
                    if (!cards.isEmpty()) {
                        for (SmartLockCard card : cards) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(card.getCardIndex());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setCardType(card.getType());
                            smartLockVO.setIndexNum(card.getCardIndexNum());
                            smartLockVO.setIdentification(card.getIdentification());
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                smartLockVO.setfAuthorizationID(card.getfAuthorizationId());
                            }

                            ResultBean<String> stringResultBean = smartLockBrandService.clearCard(smartLockVO,
                                    smartLock.getBrandId(), "card");
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            log.info("LockAppService.delAllAuth, del card, code={}, msg={}, vo={}", code, msg,
                                    JSON.toJSONString(smartLockVO));
                        }
                    }

                    // 删除指纹锁授权
                    if (!fingerprint.isEmpty()) {
                        Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                        if (optional.isPresent()) {
                            SmartLockBrand brand = optional.get();
                            // 品牌支持指纹锁
                            if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                                for (SmartLockFingerprint fg : fingerprint) {
                                    SmartLockVO smartLockVO = new SmartLockVO();
                                    smartLockVO.setSn(smartLock.getSn());
                                    smartLockVO.setIndex(fg.getFingerprintIndex());
                                    smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                    smartLockVO.setAuthInfoId(lockAuthId);
                                    smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                    // 亚略特
                                    if (smartLock.getBrandId() == 3L) {
                                        smartLockVO.setfAuthorizationID(fg.getfAuthorizationId());
                                    }

                                    ResultBean<String> stringResultBean = smartLockBrandService
                                            .clearFingerprint(smartLockVO, smartLock.getBrandId(), "fingerprint");
                                    String msg = stringResultBean.getMsg();
                                    String code = stringResultBean.getCode();
                                    log.info("LockAppService delAllAuth, del fingerprint, code={}, msg={}, vo={}",
                                            code, msg, JSON.toJSONString(smartLockVO));
                                }
                            }
                        }
                    }

                    // 删除蓝牙授权
                    if (ble != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            smartLockVO.setfAuthorizationID(ble.getfAuthorizationId());
                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.clearBle(smartLockVO, smartLock.getBrandId());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, vo={}", code, msg, JSON.toJSONString(smartLockVO));
                    }

                    // 删除人脸授权
                    if (ObjectUtil.isNotEmpty(face)) {
                        face.setSn(smartLock.getSn());
                        ResultBean<String> stringResultBean = smartLockBrandService.clearFace(face, smartLock.getBrandId());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败返回错误信息
                            return ResultBean.failedResultWithCodeAndMsg(code, msg);
                        }
//                        ossService.deleteObject("",face.getFaceImage().split("https://xj-saas-images.oss-cn-qingdao.aliyuncs.com/")[1]);
                    }

                }
            }

            // 更新公租房锁授权状态
            String houseId = smartLock.getHouseId();
            houseRepository.updateLockStatusById(houseId, 0);

            // 操作成功设置缓存，防止重复操作
            redisTemplate.opsForValue().set("lock_del_id:" + lockId, "", 1, TimeUnit.MINUTES);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockAppService delAllAuth Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 单用户删除授权
     *
     * @param lockAuthId
     * @return
     */
    @Transactional
    public ResultBean<Object> delPersonAuth(Long lockAuthId) {
        try {
            if (lockAuthId == null) {
                log.info("删除授权, 授权用户id为空");
                return ResultBean.failedResultOfParamWithMsg("授权用户id为空");
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            SmartLockAuth auth = authOpt.get();

            Optional<SmartLock> lockOptional = smartLockRepository.findById(auth.getLockId());
            if (!lockOptional.isPresent()) {
                log.info("删除授权, 智能锁不存在, LockId={}", auth.getLockId());
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
            List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
            List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
            SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
            SmartLockFace face = smartLockFaceRepository.findByLockAuthId(lockAuthId);

            log.info("删除授权, lockAuthId={}, pwd={}, cards={}, fingerprint={}, ble={}", lockAuthId, JSON.toJSONString(pwd),
                    JSON.toJSONString(cards), JSON.toJSONString(fingerprint), JSON.toJSONString(ble));
            // 删除密码授权
            if (pwd != null) {
                SmartLockVO smartLockVO = new SmartLockVO();
                smartLockVO.setSn(smartLock.getSn());
                smartLockVO.setIndex(pwd.getPwdIndex());
                smartLockVO.setAuthInfoId(lockAuthId);
                smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                smartLockVO.setIdentification(pwd.getIdentification());
                // 亚略特
                if (smartLock.getBrandId() == 3L) {
                    smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                }

                ResultBean<String> stringResultBean = smartLockBrandService.clearPassword(smartLockVO,
                        smartLock.getBrandId(), "code", lockAuthId);
                String msg = stringResultBean.getMsg();
                String code = stringResultBean.getCode();
                log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, vo={}", code, msg,
                        JSON.toJSONString(smartLockVO));
                if (code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    smartLockPwdRepository.deleteByLockAuthId(lockAuthId);
                }

            }

            // 删除卡授权
            if (!cards.isEmpty()) {
                for (SmartLockCard card : cards) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setIndex(card.getCardIndex());
                    smartLockVO.setAuthInfoId(lockAuthId);
                    smartLockVO.setCardType(card.getType());
                    smartLockVO.setIndexNum(card.getCardIndexNum());
                    smartLockVO.setIdentification(card.getIdentification());
                    // 亚略特
                    if (smartLock.getBrandId() == 3L) {
                        smartLockVO.setfAuthorizationID(card.getfAuthorizationId());
                    }

                    ResultBean<String> stringResultBean = smartLockBrandService.clearCard(smartLockVO,
                            smartLock.getBrandId(), "card");
                    String msg = stringResultBean.getMsg();
                    String code = stringResultBean.getCode();
                    log.info("LockAppService.delAllAuth, del card, code={}, msg={}, vo={}", code, msg,
                            JSON.toJSONString(smartLockVO));
                    if (code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                        smartLockCardRepository.deleteByLockAuthId(lockAuthId);
                    }
                }
            }

            // 删除指纹锁授权
            if (!fingerprint.isEmpty()) {
                Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                if (optional.isPresent()) {
                    SmartLockBrand brand = optional.get();
                    // 品牌支持指纹锁
                    if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                        for (SmartLockFingerprint fg : fingerprint) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(fg.getFingerprintIndex());
                            smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                smartLockVO.setfAuthorizationID(fg.getfAuthorizationId());
                            }

                            ResultBean<String> stringResultBean = smartLockBrandService
                                    .clearFingerprint(smartLockVO, smartLock.getBrandId(), "fingerprint");
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            log.info("LockAppService delAllAuth, del fingerprint, code={}, msg={}, vo={}",
                                    code, msg, JSON.toJSONString(smartLockVO));
                            if (code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                smartLockFingerprintRepository.deleteByLockAuthId(lockAuthId);
                            }
                        }
                    }
                }
            }

            // 删除蓝牙授权
            if (ble != null) {
                SmartLockVO smartLockVO = new SmartLockVO();
                smartLockVO.setSn(smartLock.getSn());
                smartLockVO.setAuthInfoId(lockAuthId);
                // 亚略特
                if (smartLock.getBrandId() == 3L) {
                    smartLockVO.setfAuthorizationID(ble.getfAuthorizationId());
                }

                ResultBean<String> stringResultBean = smartLockBrandService.clearBle(smartLockVO, smartLock.getBrandId());
                String msg = stringResultBean.getMsg();
                String code = stringResultBean.getCode();
                log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, vo={}", code, msg, JSON.toJSONString(smartLockVO));
                if (code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    smartLockBleRepository.deleteByLockAuthId(lockAuthId);
                }
            }

            // 删除人脸授权
            if (ObjectUtil.isNotEmpty(face)) {
                face.setSn(smartLock.getSn());
                ResultBean<String> stringResultBean = smartLockBrandService.clearFace(face, smartLock.getBrandId());
                String msg = stringResultBean.getMsg();
                String code = stringResultBean.getCode();
                log.info("LockAppService.delAllAuth, del pwd, code={}, msg={}, face={}", code, msg, JSON.toJSONString(face));
                if (code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    smartLockFaceRepository.deleteByLockAuthId(lockAuthId);
                }
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockAppService delPersonAuth Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 查询智能锁设置
     *
     * @param accessToken 权限鉴定
     * @param lockId      锁id
     * @return
     */
    public ResultBean<LockFrozenSet> findLockOptions(String accessToken, Long lockId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            LockFrozenSet set = lockFrozenSetRepository.findByLockId(lockId);

            return ResultBean.successfulResult(set);
        } catch (Exception e) {
            log.error("LockAppService lockOptionsSetup Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 智能锁设置
     *
     * @param accessToken
     * @param vo
     * @return
     */
    public ResultBean<Object> lockOptionsSetup(String accessToken, LockFrozenSetVO vo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            log.info("智能锁设置, vo={}", JSON.toJSONString(vo));
            Long lockId = vo.getLockId();
            if (lockId == null) {
                return ResultBean.failedResultWithMsg("智能锁ID为空");
            }

            LockFrozenSet existSet = lockFrozenSetRepository.findByLockId(lockId);
            if (existSet == null) {
                LockFrozenSet set = new LockFrozenSet();
                set.setLockId(vo.getLockId());
                set.setCloseDay(vo.getCloseDay());
                set.setCloseRemindContent(vo.getCloseRemindContent());
                set.setOverdueDay(vo.getOverdueDay());
                set.setOverdueStatus(vo.getOverdueStatus());
                set.setOverdueContent(vo.getOverdueContent());
                set.setOperatorId(userId);
                set.setOperatorTime(new Date());

                lockFrozenSetRepository.save(set);
            } else {
                existSet.setCloseDay(vo.getCloseDay());
                existSet.setCloseRemindContent(vo.getCloseRemindContent());
                existSet.setOverdueDay(vo.getOverdueDay());
                existSet.setOverdueStatus(vo.getOverdueStatus());
                existSet.setOverdueContent(vo.getOverdueContent());
                existSet.setOperatorId(userId);
                existSet.setOperatorTime(new Date());

                lockFrozenSetRepository.save(existSet);
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockAppService lockOptionsSetup Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 亚略特，授权/删除授权，更新用户明细状态
     *
     * @param brandId
     * @param authType      授权类型：1密码，2身份证，3 IC卡，4指纹，5蓝牙
     * @param type          操作类型：1新增，2删除
     * @param smartLockAuth
     */
    public void updateSmartLockAuthStatus(Long brandId, Integer authType, Integer type, SmartLockAuth smartLockAuth) {
        try {
            // if (brandId == 3L) {
            switch (authType.toString()) {
                case "1":
                    if (type == 1) {
                        smartLockAuth.setPwdStatus(1);
                    } else {
                        smartLockAuth.setPwdStatus(0);
                    }
                    break;
                case "2":
                    if (type == 1) {
                        smartLockAuth.setCardStatus(1);
                    } else {
                        smartLockAuth.setCardStatus(0);
                    }
                    break;
                case "3":
                    if (type == 1) {
                        smartLockAuth.setCpuStatus(1);
                    } else {
                        smartLockAuth.setCpuStatus(0);
                    }
                    break;
                case "4":
                    if (type == 1) {
                        smartLockAuth.setFingerprintStatus(1);
                    } else {
                        smartLockAuth.setFingerprintStatus(0);
                    }
                    break;
                case "5":
                    if (type == 1) {
                        smartLockAuth.setBleStatus(1);
                    } else {
                        smartLockAuth.setBleStatus(0);
                    }
                    break;
                case "6":
                    if (type == 1) {
                        smartLockAuth.setFaceStatus(1);
                    } else {
                        smartLockAuth.setFaceStatus(0);
                    }
                    break;
            }

            smartLockAuthRepository.save(smartLockAuth);
            // }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 亚略特，冻结/解冻操作，更新状态
     *
     * @param pwd
     * @param card
     * @param fg
     * @param type             1冻结，0解冻
     * @param stringResultBean
     * @param smartLockAuth
     * @param lockFrozen
     */
    public void yltUpdateStatus(SmartLockPwd pwd, SmartLockCard card, SmartLockFingerprint fg, SmartLockBle ble, SmartLockFace face, Integer type,
                                ResultBean<String> stringResultBean, SmartLockAuth smartLockAuth, LockFrozen lockFrozen, SmartLock smartLock) {
        try {
            if (pwd != null) {
                // 密码状态
                if (smartLock.getBrandId() == 3) {
                    if (type == 0) {
                        pwd.setfAuthorizationId(stringResultBean.getResultData());
                    }
                }
                pwd.setStatus(1);
                smartLockPwdRepository.save(pwd);

                // 更新用户授权状态
                if (type == 1) {
                    smartLockAuth.setPwdStatus(2);
                } else {
                    smartLockAuth.setPwdStatus(1);
                }
                smartLockAuthRepository.save(smartLockAuth);

                // 更新冻结记录
                lockFrozen.setPwdStatus(1);
                lockFrozenRepository.save(lockFrozen);
            }

            if (card != null) {
                // 卡状态
                if (smartLock.getBrandId() == 3) {
                    if (type == 0) {
                        card.setfAuthorizationId(stringResultBean.getResultData());
                    }
                }
                card.setStatus(1);
                smartLockCardRepository.save(card);

                // 更新用户授权状态
                if (type == 1) {
                    if (card.getType() == 1) {
                        smartLockAuth.setCardStatus(2);
                    } else {
                        smartLockAuth.setCpuStatus(2);
                    }
                } else {
                    if (card.getType() == 1) {
                        smartLockAuth.setCardStatus(1);
                    } else {
                        smartLockAuth.setCpuStatus(1);
                    }
                }
                smartLockAuthRepository.save(smartLockAuth);

                // 更新冻结记录
                if (card.getType() == 1) {
                    lockFrozen.setCardStatus(1);
                } else {
                    lockFrozen.setCpuStatus(1);
                }
                lockFrozenRepository.save(lockFrozen);
            }

            if (fg != null) {
                // 指纹状态
                if (smartLock.getBrandId() == 3) {
                    if (type == 0) {
                        fg.setfAuthorizationId(stringResultBean.getResultData());
                    }
                }
                fg.setStatus(1);
                smartLockFingerprintRepository.save(fg);

                // 更新用户授权状态
                if (type == 1) {
                    smartLockAuth.setFingerprintStatus(2);
                } else {
                    smartLockAuth.setFingerprintStatus(1);
                }
                smartLockAuthRepository.save(smartLockAuth);

                // 更新冻结记录
                lockFrozen.setFingerprintStatus(1);
                lockFrozenRepository.save(lockFrozen);
            }

            if (ble != null) {
                // 指纹状态
                if (smartLock.getBrandId() == 3) {
                    if (type == 0) {
                        ble.setfAuthorizationId(stringResultBean.getResultData());
                    }
                }
                ble.setStatus(1);
                smartLockBleRepository.save(ble);

                // 更新用户授权状态
                if (type == 1) {
                    smartLockAuth.setBleStatus(2);
                } else {
                    smartLockAuth.setBleStatus(1);
                }
                smartLockAuthRepository.save(smartLockAuth);

                // 更新冻结记录
                lockFrozen.setBleStatus(1);
                lockFrozenRepository.save(lockFrozen);
            }

            if (face != null) {
                face.setStatus(1);
                smartLockFaceRepository.save(face);

                // 更新用户授权状态
                if (type == 1) {
                    smartLockAuth.setFaceStatus(2);
                } else {
                    smartLockAuth.setFaceStatus(1);
                }
                smartLockAuthRepository.save(smartLockAuth);

                // 更新冻结记录
                lockFrozen.setFaceStatus(1);
                lockFrozenRepository.save(lockFrozen);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public void updateOauthNumber(Long brandId, Long lockId) {
        try {
            log.info("updateOauthNumber 更新智能锁授权人数, brandId={}, lockId={}", brandId, lockId);

            // if (brandId == 3L) {
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                log.info("updateOauthNumber 更新智能锁授权人数, 未找到锁 lockId={}", lockId);
                return;
            }
            SmartLock smartLock = lockOptional.get();
            Integer bindType = smartLock.getBindType();
            Integer bindStatus = smartLock.getBindStatus();

            int oauthNumber = 0;
            if (bindType == 1 && bindStatus == 1) {// 单位锁
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 0);

                for (SmartLockAuth auth : auths) {
                    if (auth.getPwdStatus() == 1 || auth.getFingerprintStatus() == 1 || auth.getCardStatus() == 1
                            || auth.getCpuStatus() == 1 || auth.getBleStatus() == 1 || auth.getFaceStatus() == 1) {
                        oauthNumber = oauthNumber + 1;
                    }
                }
            } else if (bindType == 2 && bindStatus == 2) {// 个人锁
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 1);

                for (SmartLockAuth auth : auths) {
                    if (auth.getPwdStatus() == 1 || auth.getFingerprintStatus() == 1 || auth.getCardStatus() == 1
                            || auth.getCpuStatus() == 1 || auth.getBleStatus() == 1 || auth.getFaceStatus() == 1) {
                        oauthNumber = oauthNumber + 1;
                    }
                }
            }

            smartLock.setOauthNumber(oauthNumber);
            smartLockRepository.save(smartLock);
            //}
        } catch (Exception e) {
            log.error("更新智能锁授权人数异常" + e.getMessage(), e);
        }
    }

    public void yltUpdateLockStatus(SmartLock smartLock, Integer type) {
        try {
            // if (smartLock.getBrandId() == 3L) {
            if (type == 1) {
                if (smartLock.getBindType() == 1) {
                    int authCount = smartLockAuthRepository.findSmartLockAuthByLockId(smartLock.getId());
                    List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindTypeAndStatus(smartLock.getId(), 0);
                    if (authCount == auths.size()) {
                        smartLock.setMechineStatus(2);
                        smartLockRepository.save(smartLock);

                        // 全部冻结时, 更新公租房锁授权状态
                        String houseId = smartLock.getHouseId();
                        houseRepository.updateLockStatusById(houseId, 4);
                    }
                } else {
                    int authCount = smartLockAuthRepository.findPersonSmartLockAuthByLockId(smartLock.getId());
                    List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindTypeAndStatus(smartLock.getId(), 1);
                    if (authCount == auths.size()) {
                        smartLock.setMechineStatus(2);
                        smartLockRepository.save(smartLock);

                        // 全部冻结时, 更新公租房锁授权状态
                        String houseId = smartLock.getHouseId();
                        houseRepository.updateLockStatusById(houseId, 4);
                    }
                }
            }

            if (type == 0) {
                // 任意授权解冻，更新智能锁设备状态
                smartLock.setMechineStatus(1);
                smartLock.setReason("");
                smartLockRepository.save(smartLock);
            }
            //}
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     * 搜索卡数据
     *
     * @param accessToken 权限鉴定
     * @param search      关键字搜索
     * @return
     */
    public ResultBean<Object> cardList(String accessToken, String search) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String sql = "select * from  m_card_warehouse where freeze_thaw_status !=2 ";
            StringBuilder where = new StringBuilder();
            if (StringUtils.isNotBlank(search)) {
                where.append(" and ( card_number like '%" + search + "%' or card_id like '%" + search + "%' )");
            }
            List<MCardWarehouse> card = jdbcTemplate.query(sql + where.toString(), new BeanPropertyRowMapper<>(MCardWarehouse.class));
            return ResultBean.successfulResult(card);
        } catch (Exception e) {
            log.error("LockAppService lockOptionsSetup Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 总后管调用 cpu卡库 冻结/解冻
     *
     * @param lockId
     * @param type   类型：0:解冻 1:冻结
     * @param reason 冻结备注
     * @return
     * @author shun
     * @date 2021年7月7日
     */
    @Transactional
    public String frozenOrUnfrozenChamada(Long lockId, Long lockAuthId, Integer type, String reason) {
        String successfulResult = "0";
        try {
            log.info("frozenOrUnfrozenChamada, lockId={}, lockAuthId={}, type={}, reason={}", lockId, lockAuthId, type, reason);

            if (lockId == null) {
                return successfulResult = "智能锁ID为空";
            }
            if (type == null) {
                return successfulResult = "操作类型为空";
            }
            if (type == 1 && StringUtils.isBlank(reason)) {
                return successfulResult = "冻结原因为空";
            }
            if (lockAuthId == null) {
                return successfulResult = "授权ID为空";
            }

            // 获取缓存
            Object redis = redisTemplate.opsForValue().get("lock_p_id:" + lockId + lockAuthId);
            if (redis != null) {
                return successfulResult = "检测有操作记录，请稍后重试";
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return successfulResult = "智能锁不存在";
            }
            SmartLock smartLock = lockOptional.get();
            Date date = new Date();

            Optional<SmartLockAuth> auths = smartLockAuthRepository.findById(lockAuthId);
            if (!auths.isPresent()) {
                return successfulResult = "授权信息有误";
            }
            SmartLockAuth smartLockAuth = auths.get();

            // 单用户授权冻结, 一次冻结密码、身份证、CPU、指纹
            SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
            List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
            List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
            SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
            if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null) {
                // 新增冻结记录
                String houseId = smartLock.getHouseId();
                // String matchUserName = smartLock.getMatchUserName();
                String communityName = smartLock.getCommunityName();
                String buildName = smartLock.getBuildName();
                String unitName = smartLock.getUnitName();
                String roomNumber = smartLock.getRoomNumber();

                LockFrozen lockFrozen = new LockFrozen();
                lockFrozen.setType(type);
                lockFrozen.setLockId(lockId);
                lockFrozen.setLockAuditId(lockAuthId);
                lockFrozen.setHouseId(houseId);
                lockFrozen.setMatchUserName(smartLockAuth.getUserName());
                lockFrozen.setCommunityName(communityName);
                lockFrozen.setBuildName(buildName);
                lockFrozen.setUnitName(unitName);
                lockFrozen.setRoomNumber(roomNumber);
                // lockFrozen.setOperationId(userId);
                lockFrozen.setOperationTime(date);
                if (StringUtils.isNotBlank(reason)) {
                    lockFrozen.setReason(reason);
                }
                LockFrozen frozenSave = lockFrozenRepository.save(lockFrozen);

                // 冻结密码
                if (pwd != null) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setIndex(pwd.getPwdIndex());
                    smartLockVO.setAuthInfoId(lockAuthId);
                    Integer authType = pwd.getAuthType();
                    if (authType == 1 || authType == 2) {
                        smartLockVO.setAuthType(LockAuthTypeEnum.NORMAL_PASS.getValue());
                    } else if (authType == 3) {
                        smartLockVO.setAuthType(LockAuthTypeEnum.TIMES_PASS.getValue());
                        smartLockVO.setTimes(pwd.getTimes());
                    }
                    smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                    smartLockVO.setLockFrozenId(frozenSave.getId());
                    smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                    smartLockVO.setIdentification(pwd.getIdentification());
                    // 亚略特
                    if (smartLock.getBrandId() == 3L) {
                        if (type == 1) {
                            smartLockVO.setfAuthorizationID(pwd.getfAuthorizationId());
                        } else {
                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                            yltVO.setfLockMAC(smartLock.getMac());
                            yltVO.setfAppUserID(pwd.getfAppUserId());
                            yltVO.setfBeginDate(DateUtils.format(pwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfEndDate(DateUtils.format(pwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfOpenByPassword(1);
                            yltVO.setfOpenByIDCard(0);
                            yltVO.setfOpenByBLE(0);
                            yltVO.setfOpenByFinger(0);
                            yltVO.setfOpenByICCard(0);
                            yltVO.setfOpenPassword(pwd.getPassword());
                            smartLockVO.setYltAuth(yltVO);
                        }
                    }

                    ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreeze(smartLockVO,
                            smartLock.getBrandId(), XzLockOperatorTypeEnum.PWD.getValue());
                    String msg = stringResultBean.getMsg();
                    String code = stringResultBean.getCode();
                    if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                        log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                        // 失败，删除冻结记录
                        lockFrozenRepository.deleteById(frozenSave.getId());
                    } else {
                        // 冻结后默认待执行
                        pwd.setStatus(0);
                        smartLockPwdRepository.save(pwd);
                        // 亚略特
                        // if (smartLock.getBrandId() == 3L) {
                        yltUpdateStatus(pwd, null, null, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                        //}
                    }
                }

                // 冻结卡
                if (!cards.isEmpty()) {
                    for (SmartLockCard card : cards) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setIndex(card.getCardIndex());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setCardType(card.getType());
                        smartLockVO.setSuspend(type);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());
                        smartLockVO.setIndexNum(card.getCardIndexNum());
                        smartLockVO.setIdentification(card.getIdentification());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            if (type == 1) {
                                smartLockVO.setfAuthorizationID(card.getfAuthorizationId());
                            } else {
                                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                yltVO.setfLockMAC(smartLock.getMac());
                                yltVO.setfAppUserID(card.getfAppUserId());
                                yltVO.setfBeginDate(DateUtils.format(card.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfEndDate(DateUtils.format(card.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfOpenByPassword(0);
                                yltVO.setfOpenByBLE(0);
                                yltVO.setfOpenByFinger(0);
                                if (card.getType() == 1) {
                                    yltVO.setfOpenByIDCard(1);
                                    yltVO.setfOpenByICCard(0);
                                } else {
                                    yltVO.setfOpenByIDCard(0);
                                    yltVO.setfOpenByICCard(1);
                                }
                                yltVO.setfIDCardID(card.getCardId());
                                yltVO.setfIDCardNumber(card.getCardNumber());
                                smartLockVO.setYltAuth(yltVO);
                            }
                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeCard(smartLockVO,
                                smartLock.getBrandId(), XzLockOperatorTypeEnum.CARD.getValue());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                        } else {
                            // 冻结后默认待执行
                            card.setStatus(0);
                            smartLockCardRepository.save(card);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            yltUpdateStatus(null, card, null, null, null, type, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                            //}
                        }
                    }
                }

                // 指纹锁


                // 蓝牙

            }

            // 更新冻结原因
            if (type == 1) {
                smartLock.setReason(reason);
            } else {
                smartLock.setReason(null);
            }

            // 更新亚略特智能锁状态
            yltUpdateLockStatus(smartLock, type);

            // 更新锁授权人数
            updateOauthNumber(smartLock.getBrandId(), lockId);

            // 操作成功设置缓存，防止重复操作
            redisTemplate.opsForValue().set("lock_p_id:" + lockId + lockAuthId, "", 1, TimeUnit.MINUTES);

            return successfulResult = "1";
        } catch (Exception e) {
            log.error("LockAppService frozenOrUnfrozenAuth Exception = {}" + e.getMessage(), e);
            return successfulResult = "2";
        }
    }

    /**
     * 总后管调用 cpu卡库  单用户删除授权
     *
     * @param lockAuthIds
     * @return
     */
    @Transactional
    public String delCardAuth(String lockAuthIds) {
        String successfulResult = "0";
        try {
            Long lockAuthId = Long.parseLong(lockAuthIds);

            if (lockAuthId == null) {
                log.info("删除授权, 授权用户id为空");
                return successfulResult = "授权用户id为空";
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            SmartLockAuth auth = authOpt.get();

            Optional<SmartLock> lockOptional = smartLockRepository.findById(auth.getLockId());
            if (!lockOptional.isPresent()) {
                log.info("删除授权, 智能锁不存在, LockId={}", auth.getLockId());
                return successfulResult = "智能锁不存在";
            }
            SmartLock smartLock = lockOptional.get();

            // SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
            List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
            List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
            SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);

            // log.info("删除授权, lockAuthId={}, pwd={}, cards={}, fingerprint={}, ble={}", lockAuthId, JSON.toJSONString(pwd),
            //         JSON.toJSONString(cards), JSON.toJSONString(fingerprint), JSON.toJSONString(ble));
            // 删除卡授权
            if (!cards.isEmpty()) {
                for (SmartLockCard card : cards) {
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setIndex(card.getCardIndex());
                    smartLockVO.setAuthInfoId(lockAuthId);
                    smartLockVO.setCardType(card.getType());
                    smartLockVO.setIndexNum(card.getCardIndexNum());
                    smartLockVO.setIdentification(card.getIdentification());
                    // 亚略特
                    if (smartLock.getBrandId() == 3L) {
                        smartLockVO.setfAuthorizationID(card.getfAuthorizationId());
                    }

                    ResultBean<String> stringResultBean = smartLockBrandService.clearCard(smartLockVO,
                            smartLock.getBrandId(), "card");
                    String msg = stringResultBean.getMsg();
                    String code = stringResultBean.getCode();
                    log.info("LockAppService.delAllAuth, del card, code={}, msg={}, vo={}", code, msg,
                            JSON.toJSONString(smartLockVO));
                }
            }
            // 删除指纹锁授权

            // 删除蓝牙授权

            return successfulResult = "1";
        } catch (Exception e) {
            log.error("LockAppService delPersonAuth Exception = {}" + e.getMessage(), e);
            return successfulResult = "2";
        }
    }

    /**
     * 查看授权指纹
     *
     * @param accessToken
     * @param lockAuthId
     * @param
     * @return
     * @author shun
     * @date 2022年7月8日
     */
    public ResultBean<AuthFingerprintVO> findAuthFingerprintStatus(String accessToken, Long lockAuthId) {
        try {
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);

            AuthFingerprintVO vo = new AuthFingerprintVO();
            if (!authOpt.isPresent()) {
                vo.setStatus(0);
                vo.setLockAuthId(lockAuthId);
                return ResultBean.successfulResult(vo);
            }

            SmartLockAuth auth = authOpt.get();
            vo.setLockAuthId(lockAuthId);
            vo.setLockId(auth.getLockId());
            if (auth.getFingerprintStatus() != null && auth.getFingerprintStatus() == 1) {
                vo.setStatus(1);
            } else {
                vo.setStatus(0);
            }
            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 产生智能锁冻结/解冻待办事项
     *
     * @param mobile     电话
     * @param remark     冻结解冻内容
     * @param type       类型 0:解冻 1:冻结
     * @param houseId    房子ID
     * @param userId     接收人
     * @param operatorId 操作人
     */
    public void addBacklogItem(String mobile, String remark, Integer type, String houseId, String userId, String operatorId, Long enterpriseId) {
        if (type == 1) {
            smsService.sendTemplateSmsWithData(mobile, smsConfig.getLockTemplateCode(), new String[]{remark});
        }


        StringBuilder sql = new StringBuilder();
        sql.append("select a.id ,  \n" +
                "a.org_id as orgId,\n" +
                "b.name AS residenceCommunityName,\n" + // 小区ID
                "c.name AS buildingNumName,\n" +
                "d.name AS unitName ,\n" +
                "a.room_number AS roomNumber \n" +
                "from  saas_house  a\n" +
                "JOIN saas_community b ON b.id = a.  residence_community_id\n" +
                "LEFT JOIN saas_community_build c ON a.building_num = c.id  \n" +
                "LEFT JOIN saas_community_build_unit d ON a.unit = d.id  \n" +
                "where 1=1");

        List<HouseVO> houseList = jdbcTemplate.query(sql.toString() + " and a.id in( '" + houseId + "') ", new BeanPropertyRowMapper<>(HouseVO.class));
        Map<String, HouseVO> houseMap = houseList.stream().collect(Collectors.toMap(HouseVO::getId, a -> a, (k1, k2) -> k1));
        String typeName = null;
        if (type == 1) {
            typeName = "智能锁已冻结";
        } else {
            typeName = "智能锁已解冻";
        }

        // 生成代办事项
        BacklogItem backlogItem = new BacklogItem();
        backlogItem.setHouseId(houseId);// 公租房id
        HouseVO house = houseMap.get(houseId);
        if (null != house) {
            backlogItem.setOrgId(house.getOrgId());// 产权单位id
            if (StringUtils.isNotEmpty(house.getResidenceCommunityName())) {
                backlogItem.setContent(house.getResidenceCommunityName() + house.getBuildingNumName()
                        + "栋" + house.getUnitName() + "单元" + house.getRoomNumber() + "号" + typeName);// 内容   房屋小区-楼栋-单元-房号
            }
        }
        if (type == 1) {
            backlogItem.setTitle("智能锁冻结");// 标题
            backlogItem.setType(32);// 类型：1公租房录入 2智能锁(租金/押金) 3其它费用账单 4资格申请-配租 5备案 6合同到期 13智能锁个人绑定确认 14门锁低电量告警 15门锁离线
            // 16资格审批 17轮候配租 18(合同)租金押金 19生成合同 20合同待确认  30 新增成员 31删除成员 32智能锁冻结  33智能锁解冻', 34 cpu卡冻结

        } else {
            backlogItem.setTitle("智能锁解冻");// 标题
            backlogItem.setType(33);// 类型：1公租房录入 2智能锁(租金/押金) 3其它费用账单 4资格申请-配租 5备案 6合同到期 13智能锁个人绑定确认 14门锁低电量告警 15门锁离线
            // 16资格审批 17轮候配租 18(合同)租金押金 19生成合同 20合同待确认  30 新增成员 31删除成员 32智能锁冻结  33智能锁解冻', 34 cpu卡冻结

        }

        backlogItem.setHandleStatus(0);// 事项处理状态：0未读/未处理  1已读/已处理
        backlogItem.setMatchUserId(userId);// 承租人id/被冻结人
        backlogItem.setOperatorId(operatorId);// 操作人id
        backlogItem.setCreateTime(new Date());// 创建时间
        backlogItem.setPhone(mobile);// 手机号
        BacklogItem save = backlogItemRepository.save(backlogItem);

        BacklogItemCard backlogItemCard = new BacklogItemCard();
        backlogItemCard.setBacklogItemId(save.getId());// 待办事项id
        if (type == 1) {
            backlogItemCard.setType((byte) 1);// 1冻结、2解冻
        } else {
            backlogItemCard.setType((byte) 2);// 1冻结、2解冻
        }
        backlogItemCard.setRemark(remark);// 冻结原因
        backlogItemCard.setOperatorTime(new Date());// 操作时间
        backlogItemCardRefRepository.save(backlogItemCard);
    }

    /**
     * 产生智能锁冻结/解冻待办事项 企业用户推送
     *
     * @param mobile     电话
     * @param remark     冻结解冻内容
     * @param type       类型 0:解冻 1:冻结
     * @param houseId    房子ID
     * @param userId     接收人
     * @param operatorId 操作人
     */
    public void addBacklogItemEnterprise(String mobile, String remark, Integer type, String houseId, String userId, String operatorId, Long enterpriseId) {
        // if (type == 1) {
        //     smsService.sendTemplateSmsWithData(mobile, smsConfig.getLockTemplateCode(), new String[]{remark});
        // }


        StringBuilder sql = new StringBuilder();
        sql.append("select a.id ,  \n" +
                "a.org_id as orgId,\n" +
                "b.name AS residenceCommunityName,\n" + // 小区ID
                "c.name AS buildingNumName,\n" +
                "d.name AS unitName ,\n" +
                "a.room_number AS roomNumber \n" +
                "from  saas_house  a\n" +
                "JOIN saas_community b ON b.id = a.  residence_community_id\n" +
                "LEFT JOIN saas_community_build c ON a.building_num = c.id  \n" +
                "LEFT JOIN saas_community_build_unit d ON a.unit = d.id  \n" +
                "where 1=1");

        List<HouseVO> houseList = jdbcTemplate.query(sql.toString() + " and a.id in( '" + houseId + "') ", new BeanPropertyRowMapper<>(HouseVO.class));
        Map<String, HouseVO> houseMap = houseList.stream().collect(Collectors.toMap(HouseVO::getId, a -> a, (k1, k2) -> k1));
        String typeName = null;
        if (type == 1) {
            typeName = "智能锁已冻结";
        } else {
            typeName = "智能锁已解冻";
        }

        // 生成代办事项
        BacklogItem backlogItem = new BacklogItem();
        backlogItem.setHouseId(houseId);// 公租房id
        HouseVO house = houseMap.get(houseId);
        if (null != house) {
            backlogItem.setOrgId(house.getOrgId());// 产权单位id
            if (StringUtils.isNotEmpty(house.getResidenceCommunityName())) {
                backlogItem.setContent(house.getResidenceCommunityName() + house.getBuildingNumName()
                        + "栋" + house.getUnitName() + "单元" + house.getRoomNumber() + "号" + typeName);// 内容   房屋小区-楼栋-单元-房号
            }
        }
        if (type == 1) {
            backlogItem.setTitle("智能锁冻结");// 标题
            backlogItem.setType(32);// 类型：1公租房录入 2智能锁(租金/押金) 3其它费用账单 4资格申请-配租 5备案 6合同到期 13智能锁个人绑定确认 14门锁低电量告警 15门锁离线
            // 16资格审批 17轮候配租 18(合同)租金押金 19生成合同 20合同待确认  30 新增成员 31删除成员 32智能锁冻结  33智能锁解冻', 34 cpu卡冻结

        } else {
            backlogItem.setTitle("智能锁解冻");// 标题
            backlogItem.setType(33);// 类型：1公租房录入 2智能锁(租金/押金) 3其它费用账单 4资格申请-配租 5备案 6合同到期 13智能锁个人绑定确认 14门锁低电量告警 15门锁离线
            // 16资格审批 17轮候配租 18(合同)租金押金 19生成合同 20合同待确认  30 新增成员 31删除成员 32智能锁冻结  33智能锁解冻', 34 cpu卡冻结

        }

        backlogItem.setHandleStatus(0);// 事项处理状态：0未读/未处理  1已读/已处理
        backlogItem.setMatchUserId(userId);// 承租人id/被冻结人
        backlogItem.setOperatorId(operatorId);// 操作人id
        backlogItem.setCreateTime(new Date());// 创建时间
        backlogItem.setPhone(mobile);// 手机号
        // BacklogItem save = backlogItemRepository.save(backlogItem);

        // BacklogItemCard backlogItemCard = new BacklogItemCard();
        // backlogItemCard.setBacklogItemId(save.getId());//待办事项id
        // if (type == 1) {
        //    backlogItemCard.setType((byte) 1);//1冻结、2解冻
        //} else {
        //    backlogItemCard.setType((byte) 2);//1冻结、2解冻
        //}
        // backlogItemCard.setRemark(remark);//冻结原因
        // backlogItemCard.setOperatorTime(new Date());//操作时间
        // backlogItemCardRefRepository.save(backlogItemCard);

        //    企业消息推送
        String sqlStr = "SELECT\n" +
                "\tb.id,\n" +
                "\tb.mobile AS phone \n" +
                "FROM\n" +
                "\tsaas_backlog_item_message_user a\n" +
                "\tLEFT JOIN saas_user b ON b.id = a.user_id \n" +
                "\tLEFT JOIN saas_department_hierarchy dh ON dh.org_id = a.org_id\n" +
                "WHERE\n" +
                "\ta.org_id = ? and a.type = 2";

        List<AppUser> query = jdbcTemplate.query(sqlStr, new BeanPropertyRowMapper<>(AppUser.class), enterpriseId);
        for (AppUser user : query) {
            BacklogItem backlogItem1 = new BacklogItem();
            BeanUtils.copyProperties(backlogItem, backlogItem1);
            backlogItem1.setMatchUserId(user.getId());// 承租人
            backlogItem1.setPhone(user.getPhone());// 承租人
            backlogItem1.setId(null);
            BacklogItem save = backlogItemRepository.save(backlogItem1);

            BacklogItemCard backlogItemCard = new BacklogItemCard();
            backlogItemCard.setBacklogItemId(save.getId());// 待办事项id
            if (type == 1) {
                backlogItemCard.setType((byte) 1);// 1冻结、2解冻
            } else {
                backlogItemCard.setType((byte) 2);// 1冻结、2解冻
            }
            backlogItemCard.setRemark(remark);// 冻结原因
            backlogItemCard.setOperatorTime(new Date());// 操作时间
            backlogItemCardRefRepository.save(backlogItemCard);
        }
    }

    public String relationTagName(Integer houseType, Integer relationTag) {
        String name = null;
        if (houseType == 1) {
            switch (relationTag) {

                case 1:
                    name = "户主";
                    break;
                case 2:
                    name = "妻子";
                    break;
                case 3:
                    name = "丈夫";
                    break;
                case 4:
                    name = "儿子";
                    break;
                case 5:
                    name = "儿媳";
                    break;
                case 6:
                    name = "女儿";
                    break;
                case 7:
                    name = "女婿";
                    break;

                case 8:
                    name = "父亲";
                    break;
                case 9:
                    name = "母亲";
                    break;
                case 10:
                    name = "哥哥";
                    break;
                case 11:
                    name = "嫂子";
                    break;
                case 12:
                    name = "姐姐";
                    break;
                case 13:
                    name = "姐夫";
                    break;
                case 14:
                    name = "弟弟";
                    break;
                case 15:
                    name = "弟媳";
                    break;
                case 16:
                    name = "妹妹";
                    break;
                case 17:
                    name = "妹夫";
                    break;
                case 18:
                    name = "同事";
                    break;

            }


        } else {
            switch (relationTag) {
                case 1:
                    name = "妻子";
                    break;
                case 2:
                    name = "丈夫";
                    break;
                case 3:
                    name = "儿子";
                    break;
                case 4:
                    name = "儿媳";
                    break;
                case 5:
                    name = "女儿";
                    break;
                case 6:
                    name = "女婿";
                    break;
                case 7:
                    name = "父亲";
                    break;
                case 8:
                    name = "母亲";
                    break;
                case 9:
                    name = "同事";
                    break;
                case 10:
                    name = "哥哥";
                    break;
                case 11:
                    name = "嫂子";
                    break;
                case 12:
                    name = "姐姐";
                    break;
                case 13:
                    name = "姐夫";
                    break;
                case 14:
                    name = "弟弟";
                    break;
                case 15:
                    name = "弟媳";
                    break;
                case 16:
                    name = "妹妹";
                    break;
                case 17:
                    name = "妹夫";
                    break;
                case 18:
                    name = "其他亲属";
                    break;
                case 19:
                    name = "朋友";
                    break;
                case 20:
                    name = "非亲属";
                    break;

            }
        }

        return name;

    }

    /**
     * 账户管理 - 账户延期
     *
     * @param accessToken
     * @param houseId           房屋id
     * @param cause             延期原因
     * @param deferredStartTime 开始时间
     * @param deferredEndTime   结束时间
     * @return
     */
    @Transactional
    public ResultBean<Object> postpone(String accessToken, String houseId, String cause, String deferredStartTime, String deferredEndTime) {

        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }

        String userId = token.getId();
        Long enterpriseId = token.getEnterpriseId();

        if (StringUtils.isEmpty(houseId) || StringUtils.isEmpty(cause)
                || StringUtils.isEmpty(deferredStartTime) || StringUtils.isEmpty(deferredEndTime)) {
            return ResultBean.failedResultOfParamWithMsg("参数有误");
        }
        Date deferredStartDate = DateUtils.convert(deferredStartTime, DateUtils.FORMAT_DATETIME_14);
        Date deferredEndDate = DateUtils.convert(deferredEndTime, DateUtils.FORMAT_DATETIME_14);
        Optional<House> byId = houseRepository.findById(houseId);
        if (!byId.isPresent()) {
            return ResultBean.failedResultWithMsg("房屋未找到");
        }
        List<SmartLock> byHouseId = smartLockRepository.findByHouseId(houseId);
        if (byHouseId.isEmpty()) {
            return ResultBean.failedResultWithMsg("房屋未安装智能锁无法延期！");
        }

        List<SmartLockAuth> smartLockAuths = new ArrayList<>();
        House house = byId.get();
        String housemateId = house.getHousemateId();
        if (StringUtils.isNotBlank(housemateId)) {
            smartLockAuths = smartLockAuthRepository.findBySubHouseId(houseId);
        } else {
            smartLockAuths = smartLockAuthRepository.findByHouseIdAndBindType(houseId, 0);
        }

        if (smartLockAuths.isEmpty()) {
            return ResultBean.failedResultWithMsg("当前智能锁无授权");
        }
        Long lockId = smartLockAuths.get(0).getLockId();
        if (lockId == null) {
            return ResultBean.failedResultWithMsg("未查到智能锁");
        }

        Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
        if (!lockOptional.isPresent()) {
            return ResultBean.failedResultWithMsg("智能锁不存在");
        }
        // 系统ID
        String systemUser = redisService.getSystemUser();
        SmartLock smartLock = lockOptional.get();
        Date date = new Date();
        String reason = "账户延期";
        Long orgId = token.getEnterpriseId();


        if (deferredEndDate.getTime() < date.getTime()) {
            return ResultBean.failedResultWithMsg("延期结束时间不能小于当前时间");
        }
        List<HouseRemainingRelation> remainingRelations = houseRemainingRelationRepository.findByHouseId(houseId);
        if (remainingRelations.isEmpty()) {
            return ResultBean.failedResultWithMsg("当前房屋账户状态异常，请联系管理员");
        }
        List<Long> remIds = remainingRelations.stream().map(HouseRemainingRelation::getRemainingId).collect(Collectors.toList());
        List<HouseRemaining> rem = houseRemainingRepository.findByIdIn(remIds);
        if (rem.isEmpty()) {
            return ResultBean.failedResultWithMsg("当前房屋账户不存在，请联系管理员");
        }
        Boolean flag = true;
        for (HouseRemaining remaining : rem) {
            if (remaining.getOrgId().equals(orgId)) {
                // 延期
                if (remaining.getStatus().equals(RemainingStatusEnum.POSTPONE.getValue()) ) {
                    if (deferredEndDate.getTime() <= remaining.getDeferredEndTime().getTime()) {
                        throw new BizException("延住时间不能小于当前账户延住时间");
                    }
                }
                if (remaining.getStatus().equals(RemainingStatusEnum.NORMAL.getValue())){
                    throw new BizException("账户正常状态不可延住");
                }

                remaining.setStatus(RemainingStatusEnum.POSTPONE.getValue());
                remaining.setDeferredStartTime(deferredStartDate);
                remaining.setDeferredEndTime(deferredEndDate);

                HouseRemainingPostpone remPostpone = new HouseRemainingPostpone();
                remPostpone.setRemainingId(remaining.getId());
                remPostpone.setPostponeType(0);
                remPostpone.setOperatorId(userId);
                remPostpone.setLastUpdateTime(date);
                remPostpone.setCause(cause);
                remPostpone.setDeferredStartTime(deferredStartDate);
                remPostpone.setDeferredEndTime(deferredEndDate);
                remPostpone.setCancelStatus(0);
                houseRemainingPostponeRepository.save(remPostpone);

                houseRemainingRepository.save(remaining);
            } else {
                if (remaining.getStatus() == 7) {
                    flag = false;
                }
            }

        }


        if (flag) {
            // 已冻结用户
            List<SmartLockAuth> lockAuths = smartLockAuths.stream().filter(m -> m.getPwdStatus() == 2 || m.getFingerprintStatus() == 2
                    || m.getCardStatus() == 2 || m.getCpuStatus() == 2 || m.getBleStatus() == 2 || m.getFaceStatus() == 2).distinct().collect(Collectors.toList());

            if (!lockAuths.isEmpty()) {
                for (SmartLockAuth auth : lockAuths) {
                    Long lockAuthId = auth.getId();
                    boolean adopt = true;

                    HouseLockFrozenLog lock = houseLockFrozenLogRepository.findByLockIdAndLockAuditIdAndType(lockId, lockAuthId, 1);

                    if (null != lock) {
                        // 最后一次冻结记录是否属于系统自动冻结
                        if (lock.getOperationState() == 1) {
                            adopt = false;
                        }

                    }
                    // 获取缓存
                    Object redis = redisTemplate.opsForValue().get("lock_p_id:" + lockId + lockAuthId);
                    if (redis != null) {
                        return ResultBean.failedResultWithMsg("检测有操作记录，请稍后重试");
                    }

                    if (adopt) {
                        // 单用户授权冻结, 一次冻结密码、身份证、CPU、指纹
                        SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
                        List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
                        List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
                        SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
                        SmartLockFace face = smartLockFaceRepository.findByLockAuthId(lockAuthId);
                        if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null || face != null) {
                            // 新增冻结记录
                            // String matchUserName = smartLock.getMatchUserName();
                            String communityName = smartLock.getCommunityName();
                            String buildName = smartLock.getBuildName();
                            String unitName = smartLock.getUnitName();
                            String roomNumber = smartLock.getRoomNumber();

                            LockFrozen lockFrozen = new LockFrozen();
                            // 0解冻 1冻结
                            lockFrozen.setType(0);
                            lockFrozen.setLockId(lockId);
                            lockFrozen.setLockAuditId(lockAuthId);
                            lockFrozen.setHouseId(houseId);
                            lockFrozen.setMatchUserName(auth.getUserName());
                            lockFrozen.setCommunityName(communityName);
                            lockFrozen.setBuildName(buildName);
                            lockFrozen.setUnitName(unitName);
                            lockFrozen.setRoomNumber(roomNumber);
                            lockFrozen.setOperationId(userId);
                            lockFrozen.setOperationTime(date);
                            if (StringUtils.isNotBlank(reason)) {
                                lockFrozen.setReason(reason);
                            }
                            LockFrozen frozenSave = lockFrozenRepository.save(lockFrozen);

                            // 冻结密码
                            if (pwd != null) {
                                SmartLockVO smartLockVO = new SmartLockVO();
                                smartLockVO.setSn(smartLock.getSn());
                                smartLockVO.setIndex(pwd.getPwdIndex());
                                smartLockVO.setAuthInfoId(lockAuthId);
                                Integer authType = pwd.getAuthType();
                                if (authType == 1 || authType == 2) {
                                    smartLockVO.setAuthType(LockAuthTypeEnum.NORMAL_PASS.getValue());
                                } else if (authType == 3) {
                                    smartLockVO.setAuthType(LockAuthTypeEnum.TIMES_PASS.getValue());
                                    smartLockVO.setTimes(pwd.getTimes());
                                }
                                smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                                smartLockVO.setLockFrozenId(frozenSave.getId());
                                smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                                smartLockVO.setIdentification(pwd.getIdentification());
                                smartLockVO.setPwdType(pwd.getType());
                                // 亚略特
                                if (smartLock.getBrandId() == 3L) {
                                    YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                    yltVO.setfLockMAC(smartLock.getMac());
                                    yltVO.setfAppUserID(pwd.getfAppUserId());
                                    yltVO.setfBeginDate(DateUtils.format(pwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfEndDate(DateUtils.format(pwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfOpenByPassword(1);
                                    yltVO.setfOpenByIDCard(0);
                                    yltVO.setfOpenByBLE(0);
                                    yltVO.setfOpenByFinger(0);
                                    yltVO.setfOpenByICCard(0);
                                    yltVO.setfOpenPassword(pwd.getPassword());
                                    smartLockVO.setYltAuth(yltVO);
                                }

                                ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreeze(smartLockVO,
                                        smartLock.getBrandId(), XzLockOperatorTypeEnum.PWD.getValue());
                                String msg = stringResultBean.getMsg();
                                String code = stringResultBean.getCode();
                                if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                    log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                    // 失败，删除冻结记录
                                    lockFrozenRepository.deleteById(frozenSave.getId());
                                } else {
                                    // 冻结后默认待执行
                                    pwd.setStatus(0);
                                    smartLockPwdRepository.save(pwd);
                                    // 亚略特
                                    // if (smartLock.getBrandId() == 3L) {
                                    yltUpdateStatus(pwd, null, null, null, null, 0, stringResultBean, auth, lockFrozen, smartLock);
                                    //}
                                }
                            }

                            // 冻结卡
                            if (!cards.isEmpty()) {
                                for (SmartLockCard card : cards) {
                                    SmartLockVO smartLockVO = new SmartLockVO();
                                    smartLockVO.setSn(smartLock.getSn());
                                    smartLockVO.setIndex(card.getCardIndex());
                                    smartLockVO.setAuthInfoId(lockAuthId);
                                    smartLockVO.setCardType(card.getType());
                                    smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                                    smartLockVO.setLockFrozenId(frozenSave.getId());
                                    smartLockVO.setIndexNum(card.getCardIndexNum());
                                    smartLockVO.setIdentification(card.getIdentification());
                                    // 亚略特
                                    if (smartLock.getBrandId() == 3L) {
                                        YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                        yltVO.setfLockMAC(smartLock.getMac());
                                        yltVO.setfAppUserID(card.getfAppUserId());
                                        yltVO.setfBeginDate(DateUtils.format(card.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfEndDate(DateUtils.format(card.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfOpenByPassword(0);
                                        yltVO.setfOpenByBLE(0);
                                        yltVO.setfOpenByFinger(0);
                                        if (card.getType() == 1) {
                                            yltVO.setfOpenByIDCard(1);
                                            yltVO.setfOpenByICCard(0);
                                        } else {
                                            yltVO.setfOpenByIDCard(0);
                                            yltVO.setfOpenByICCard(1);
                                        }
                                        yltVO.setfIDCardID(card.getCardId());
                                        yltVO.setfIDCardNumber(card.getCardNumber());
                                        smartLockVO.setYltAuth(yltVO);

                                    }

                                    ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeCard(smartLockVO,
                                            smartLock.getBrandId(), XzLockOperatorTypeEnum.CARD.getValue());
                                    String msg = stringResultBean.getMsg();
                                    String code = stringResultBean.getCode();
                                    if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                        log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                        // 失败，删除冻结记录
                                        lockFrozenRepository.deleteById(frozenSave.getId());
                                    } else {
                                        // 冻结后默认待执行
                                        card.setStatus(0);
                                        smartLockCardRepository.save(card);
                                        // 亚略特
                                        // if (smartLock.getBrandId() == 3L) {
                                        yltUpdateStatus(null, card, null, null, null, 0, stringResultBean, auth, lockFrozen, smartLock);
                                        //}
                                    }
                                }
                            }

                            // 指纹锁
                            if (!fingerprint.isEmpty()) {
                                Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                                if (optional.isPresent()) {
                                    SmartLockBrand brand = optional.get();
                                    // 品牌支持指纹锁
                                    if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                                        for (SmartLockFingerprint fg : fingerprint) {
                                            SmartLockVO smartLockVO = new SmartLockVO();
                                            smartLockVO.setSn(smartLock.getSn());
                                            smartLockVO.setIndex(fg.getFingerprintIndex());
                                            smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                            smartLockVO.setAuthInfoId(lockAuthId);
                                            smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                                            smartLockVO.setLockFrozenId(frozenSave.getId());
                                            smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                            // 亚略特
                                            if (smartLock.getBrandId() == 3L) {
                                                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                                yltVO.setfLockMAC(smartLock.getMac());
                                                yltVO.setfAppUserID(fg.getfAppUserId());
                                                yltVO.setfBeginDate(DateUtils.format(fg.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                                yltVO.setfEndDate(DateUtils.format(fg.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                                yltVO.setfOpenByPassword(0);
                                                yltVO.setfOpenByIDCard(0);
                                                yltVO.setfOpenByBLE(0);
                                                yltVO.setfOpenByFinger(1);
                                                yltVO.setfOpenByICCard(0);
                                                yltVO.setfFingerFeature(fg.getFingerprint());
                                                smartLockVO.setYltAuth(yltVO);

                                            }

                                            ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFingerprint(
                                                    smartLockVO, smartLock.getBrandId(), XzLockOperatorTypeEnum.FINGERPRINT.getValue());
                                            String msg = stringResultBean.getMsg();
                                            String code = stringResultBean.getCode();
                                            if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                                                log.error("LockAppService deleteUser---> " + msg);
                                                // 失败，删除冻结记录
                                                lockFrozenRepository.deleteById(frozenSave.getId());
                                            } else {
                                                // 冻结后默认待执行
                                                fg.setStatus(0);
                                                smartLockFingerprintRepository.save(fg);
                                                // 亚略特
                                                // if (smartLock.getBrandId() == 3L) {
                                                yltUpdateStatus(null, null, fg, null, null, 0, stringResultBean, auth, lockFrozen, smartLock);
                                                //}
                                            }
                                        }
                                    }
                                }
                            }

                            // 蓝牙
                            if (ble != null) {
                                SmartLockVO smartLockVO = new SmartLockVO();
                                smartLockVO.setIdentification(ble.getIdentification());
                                smartLockVO.setSn(smartLock.getSn());
                                smartLockVO.setAuthInfoId(lockAuthId);
                                smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                                smartLockVO.setLockFrozenId(frozenSave.getId());
                                // 亚略特
                                if (smartLock.getBrandId() == 3L) {
                                    YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                    yltVO.setfLockMAC(smartLock.getMac());
                                    yltVO.setfAppUserID(ble.getfAppUserId());
                                    yltVO.setfBeginDate(DateUtils.format(ble.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfEndDate(DateUtils.format(ble.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                    yltVO.setfOpenByPassword(0);
                                    yltVO.setfOpenByIDCard(0);
                                    yltVO.setfOpenByBLE(1);
                                    yltVO.setfOpenByFinger(0);
                                    yltVO.setfOpenByICCard(0);
                                    smartLockVO.setYltAuth(yltVO);

                                }

                                ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeBle(smartLockVO, smartLock.getBrandId());
                                String msg = stringResultBean.getMsg();
                                String code = stringResultBean.getCode();
                                if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                    log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                    // 失败，删除冻结记录
                                    lockFrozenRepository.deleteById(frozenSave.getId());
                                    return ResultBean.failedResultWithCodeAndMsg(code, msg);
                                } else {
                                    // 冻结后默认待执行
                                    ble.setStatus(0);
                                    smartLockBleRepository.save(ble);
                                    // 亚略特
                                    // if (smartLock.getBrandId() == 3L) {
                                    yltUpdateStatus(null, null, null, ble, null, 0, stringResultBean, auth, lockFrozen, smartLock);
                                    //}
                                }
                            }

                            // 人脸
                            if (face != null) {
                                SmartLockVO smartLockVO = new SmartLockVO();
                                smartLockVO.setSn(smartLock.getSn());
                                smartLockVO.setAuthInfoId(lockAuthId);
                                smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                                smartLockVO.setLockFrozenId(frozenSave.getId());

                                face.setSn(smartLock.getSn());
                                ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFace(smartLockVO, face, smartLock.getBrandId());
                                String resultData = stringResultBean.getResultData();
                                String msg = stringResultBean.getMsg();
                                String code = stringResultBean.getCode();
                                if (!code.equals(com.mzj.saas.commons.StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                    log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                    // 失败，删除冻结记录
                                    lockFrozenRepository.deleteById(frozenSave.getId());
                                } else {
                                    if (StrUtil.isNotEmpty(resultData)) {
                                        if (smartLock.getBrandId() == 8L) {
                                            String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                                            face.setIdentification(phoneNo);
                                            String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                                            face.setKeyId(keyId);
                                        } else {
                                            face.setIdentification(resultData);
                                            face.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
                                        }
                                    }
                                    // 冻结后默认待执行
                                    face.setStatus(0);
                                    smartLockFaceRepository.save(face);
                                    // 亚略特
                                    // if (smartLock.getBrandId() == 3L) {
                                    yltUpdateStatus(null, null, null, null, face, 0, stringResultBean, auth, lockFrozen, smartLock);
                                    //}
                                }
                            }

                        }


                        smartLock.setReason(null);

                        //  写入冻结日志表
                        HouseLockFrozenLog houseLockFrozenLog = new HouseLockFrozenLog();
                        houseLockFrozenLog.setType(0);// 操作类型: 0:解冻 1:冻结
                        houseLockFrozenLog.setLockId(lockId);// 智能锁绑定id
                        houseLockFrozenLog.setHouseId(smartLock.getHouseId()); // 公租房id
                        houseLockFrozenLog.setLockAuditId(lockAuthId); // 授权信息id
                        houseLockFrozenLog.setOperationId(userId); // 冻结操作人
                        houseLockFrozenLog.setOperationTime(new Date()); // 操作时间
                        houseLockFrozenLogRepository.save(houseLockFrozenLog);


                        /**
                         * 产生智能锁冻结/解冻待办事项
                         */
                        addBacklogItem(auth.getMobile(), reason, 0, smartLock.getHouseId(), auth.getAuthorUserId(), userId, enterpriseId);

                        // 操作成功设置缓存，防止重复操作
                        redisTemplate.opsForValue().set("lock_p_id:" + lockId + lockAuthId, "", 1, TimeUnit.MINUTES);
                    }
                }
            }

            // 更新亚略特智能锁状态
            yltUpdateLockStatus(smartLock, 0);

            // 更新锁授权人数
            updateOauthNumber(smartLock.getBrandId(), lockId);
        }
        return ResultBean.successfulResult(null);
    }

    /**
     * 账户管理 - 账户取消延期冻结
     *
     * @param accessToken
     * @param houseId           房屋id
     * @param cause             延期原因
     * @return
     */
    public ResultBean<Object> cancelpostpone(String accessToken, String houseId, String cause) {

        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }

        String userId = token.getId();
        Long enterpriseId = token.getEnterpriseId();

        if (StringUtils.isEmpty(houseId) || StringUtils.isEmpty(cause)) {
            return ResultBean.failedResultOfParamWithMsg("参数有误");
        }
        Optional<House> byId = houseRepository.findById(houseId);
        if (!byId.isPresent()) {
            return ResultBean.failedResultWithMsg("房屋未找到");
        }
        List<SmartLock> byHouseId = smartLockRepository.findByHouseId(houseId);
        if (byHouseId.isEmpty()) {
            return ResultBean.failedResultWithMsg("房屋未安装智能锁无法取消延期！");
        }

        List<SmartLockAuth> smartLockAuths = new ArrayList<>();
        House house = byId.get();
        String housemateId = house.getHousemateId();
        if (StringUtils.isNotBlank(housemateId)) {
            smartLockAuths = smartLockAuthRepository.findBySubHouseId(houseId);
        } else {
            smartLockAuths = smartLockAuthRepository.findByHouseIdAndBindType(houseId, 0);
        }

        if (smartLockAuths.isEmpty()) {
            return ResultBean.failedResultWithMsg("当前智能锁无授权");
        }
        Long lockId = smartLockAuths.get(0).getLockId();
        if (lockId == null) {
            return ResultBean.failedResultWithMsg("未查到智能锁");
        }

        Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
        if (!lockOptional.isPresent()) {
            return ResultBean.failedResultWithMsg("智能锁不存在");
        }
        // 系统ID
        SmartLock smartLock = lockOptional.get();
        Date date = new Date();
        String reason = "账户取消延期";

        List<HouseRemainingRelation> remainingRelations = houseRemainingRelationRepository.findByHouseId(houseId);
        if (remainingRelations.isEmpty()) {
            return ResultBean.failedResultWithMsg("当前房屋账户状态异常，请联系管理员");
        }

        // 已解结用户
        List<SmartLockAuth> lockAuths = smartLockAuths.stream().filter(m -> m.getPwdStatus() == 1 || m.getFingerprintStatus() == 1
                || m.getCardStatus() == 1 || m.getCpuStatus() == 1 || m.getBleStatus() == 1 || m.getFaceStatus() ==1 ).distinct().collect(Collectors.toList());

        if (!lockAuths.isEmpty()) {
            for (SmartLockAuth auth : lockAuths) {
                Long lockAuthId = auth.getId();
                // 获取缓存
                Object redis = redisTemplate.opsForValue().get("lock_p_id:" + lockId + lockAuthId);
                if (redis != null) {
                    return ResultBean.failedResultWithMsg("检测有操作记录，请稍后重试");
                }

                // 单用户授权冻结, 一次冻结密码、身份证、CPU、指纹
                SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
                List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
                List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
                SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
                SmartLockFace face = smartLockFaceRepository.findByLockAuthId(lockAuthId);
                if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null || face != null) {
                    // 新增冻结记录
                    // String matchUserName = smartLock.getMatchUserName();
                    String communityName = smartLock.getCommunityName();
                    String buildName = smartLock.getBuildName();
                    String unitName = smartLock.getUnitName();
                    String roomNumber = smartLock.getRoomNumber();

                    LockFrozen lockFrozen = new LockFrozen();
                    //:1冻结 2解冻
                    lockFrozen.setType(1);
                    lockFrozen.setLockId(lockId);
                    lockFrozen.setLockAuditId(lockAuthId);
                    lockFrozen.setHouseId(houseId);
                    lockFrozen.setMatchUserName(auth.getUserName());
                    lockFrozen.setCommunityName(communityName);
                    lockFrozen.setBuildName(buildName);
                    lockFrozen.setUnitName(unitName);
                    lockFrozen.setRoomNumber(roomNumber);
                    lockFrozen.setOperationId(userId);
                    lockFrozen.setOperationTime(date);
                    if (StringUtils.isNotBlank(reason)) {
                        lockFrozen.setReason(reason);
                    }
                    LockFrozen frozenSave = lockFrozenRepository.save(lockFrozen);

                    // 冻结密码
                    if (pwd != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setIndex(pwd.getPwdIndex());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        Integer authType = pwd.getAuthType();
                        if (authType == 1 || authType == 2) {
                            smartLockVO.setAuthType(LockAuthTypeEnum.NORMAL_PASS.getValue());
                        } else if (authType == 3) {
                            smartLockVO.setAuthType(LockAuthTypeEnum.TIMES_PASS.getValue());
                            smartLockVO.setTimes(pwd.getTimes());
                        }
                        smartLockVO.setSuspend(1);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());
                        smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                        smartLockVO.setIdentification(pwd.getIdentification());
                        smartLockVO.setPwdType(pwd.getType());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                            yltVO.setfLockMAC(smartLock.getMac());
                            yltVO.setfAppUserID(pwd.getfAppUserId());
                            yltVO.setfBeginDate(DateUtils.format(pwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfEndDate(DateUtils.format(pwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfOpenByPassword(1);
                            yltVO.setfOpenByIDCard(0);
                            yltVO.setfOpenByBLE(0);
                            yltVO.setfOpenByFinger(0);
                            yltVO.setfOpenByICCard(0);
                            yltVO.setfOpenPassword(pwd.getPassword());
                            smartLockVO.setYltAuth(yltVO);
                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreeze(smartLockVO,
                                smartLock.getBrandId(), XzLockOperatorTypeEnum.PWD.getValue());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                        } else {
                            // 冻结后默认待执行
                            pwd.setStatus(0);
                            smartLockPwdRepository.save(pwd);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            yltUpdateStatus(pwd, null, null, null, null, 1, stringResultBean, auth, lockFrozen, smartLock);
                            //}
                        }
                    }

                    // 冻结卡
                    if (!cards.isEmpty()) {
                        for (SmartLockCard card : cards) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(card.getCardIndex());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setCardType(card.getType());
                            smartLockVO.setSuspend(1);// 0:解冻 1:冻结
                            smartLockVO.setLockFrozenId(frozenSave.getId());
                            smartLockVO.setIndexNum(card.getCardIndexNum());
                            smartLockVO.setIdentification(card.getIdentification());
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                yltVO.setfLockMAC(smartLock.getMac());
                                yltVO.setfAppUserID(card.getfAppUserId());
                                yltVO.setfBeginDate(DateUtils.format(card.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfEndDate(DateUtils.format(card.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfOpenByPassword(0);
                                yltVO.setfOpenByBLE(0);
                                yltVO.setfOpenByFinger(0);
                                if (card.getType() == 1) {
                                    yltVO.setfOpenByIDCard(1);
                                    yltVO.setfOpenByICCard(0);
                                } else {
                                    yltVO.setfOpenByIDCard(0);
                                    yltVO.setfOpenByICCard(1);
                                }
                                yltVO.setfIDCardID(card.getCardId());
                                yltVO.setfIDCardNumber(card.getCardNumber());
                                smartLockVO.setYltAuth(yltVO);

                            }

                            ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeCard(smartLockVO,
                                    smartLock.getBrandId(), XzLockOperatorTypeEnum.CARD.getValue());
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                                // 失败，删除冻结记录
                                lockFrozenRepository.deleteById(frozenSave.getId());
                            } else {
                                // 冻结后默认待执行
                                card.setStatus(0);
                                smartLockCardRepository.save(card);
                                // 亚略特
                                // if (smartLock.getBrandId() == 3L) {
                                yltUpdateStatus(null, card, null, null, null, 1, stringResultBean, auth, lockFrozen, smartLock);
                                //}
                            }
                        }
                    }

                    // 指纹锁
                    if (!fingerprint.isEmpty()) {
                        Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                        if (optional.isPresent()) {
                            SmartLockBrand brand = optional.get();
                            // 品牌支持指纹锁
                            if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                                for (SmartLockFingerprint fg : fingerprint) {
                                    SmartLockVO smartLockVO = new SmartLockVO();
                                    smartLockVO.setSn(smartLock.getSn());
                                    smartLockVO.setIndex(fg.getFingerprintIndex());
                                    smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                    smartLockVO.setAuthInfoId(lockAuthId);
                                    smartLockVO.setSuspend(1);// 0:解冻 1:冻结
                                    smartLockVO.setLockFrozenId(frozenSave.getId());
                                    smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                    // 亚略特
                                    if (smartLock.getBrandId() == 3L) {
                                        YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                        yltVO.setfLockMAC(smartLock.getMac());
                                        yltVO.setfAppUserID(fg.getfAppUserId());
                                        yltVO.setfBeginDate(DateUtils.format(fg.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfEndDate(DateUtils.format(fg.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfOpenByPassword(0);
                                        yltVO.setfOpenByIDCard(0);
                                        yltVO.setfOpenByBLE(0);
                                        yltVO.setfOpenByFinger(1);
                                        yltVO.setfOpenByICCard(0);
                                        yltVO.setfFingerFeature(fg.getFingerprint());
                                        smartLockVO.setYltAuth(yltVO);

                                    }

                                    ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFingerprint(
                                            smartLockVO, smartLock.getBrandId(), XzLockOperatorTypeEnum.FINGERPRINT.getValue());
                                    String msg = stringResultBean.getMsg();
                                    String code = stringResultBean.getCode();
                                    if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                                        log.error("LockAppService deleteUser---> " + msg);
                                        // 失败，删除冻结记录
                                        lockFrozenRepository.deleteById(frozenSave.getId());
                                    } else {
                                        // 冻结后默认待执行
                                        fg.setStatus(0);
                                        smartLockFingerprintRepository.save(fg);
                                        // 亚略特
                                        // if (smartLock.getBrandId() == 3L) {
                                        yltUpdateStatus(null, null, fg, null, null, 1, stringResultBean, auth, lockFrozen, smartLock);
                                        //}
                                    }
                                }
                            }
                        }
                    }

                    // 蓝牙
                    if (ble != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setIdentification(ble.getIdentification());
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setSuspend(1);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                            yltVO.setfLockMAC(smartLock.getMac());
                            yltVO.setfAppUserID(ble.getfAppUserId());
                            yltVO.setfBeginDate(DateUtils.format(ble.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfEndDate(DateUtils.format(ble.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfOpenByPassword(0);
                            yltVO.setfOpenByIDCard(0);
                            yltVO.setfOpenByBLE(1);
                            yltVO.setfOpenByFinger(0);
                            yltVO.setfOpenByICCard(0);
                            smartLockVO.setYltAuth(yltVO);

                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeBle(smartLockVO, smartLock.getBrandId());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                            return ResultBean.failedResultWithCodeAndMsg(code, msg);
                        } else {
                            // 冻结后默认待执行
                            ble.setStatus(0);
                            smartLockBleRepository.save(ble);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            yltUpdateStatus(null, null, null, ble, null, 1, stringResultBean, auth, lockFrozen, smartLock);
                            //}
                        }
                    }

                    // 人脸
                    if (face != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setSuspend(1);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());

                        face.setSn(smartLock.getSn());
                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFace(smartLockVO, face, smartLock.getBrandId());
                        String resultData = stringResultBean.getResultData();
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(com.mzj.saas.commons.StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.error("LockAppService frozenOrUnfrozenAuth---> " + msg);
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                        } else {
                            if (StrUtil.isNotEmpty(resultData)) {
                                if (smartLock.getBrandId() == 8L) {
                                    String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                                    face.setIdentification(phoneNo);
                                    String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                                    face.setKeyId(keyId);
                                } else {
                                    face.setIdentification(resultData);
                                    face.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
                                }
                            }
                            // 冻结后默认待执行
                            face.setStatus(0);
                            smartLockFaceRepository.save(face);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            yltUpdateStatus(null, null, null, null, face, 1, stringResultBean, auth, lockFrozen, smartLock);
                            //}
                        }
                    }

                    smartLock.setReason(cause);

                    //  写入冻结日志表
                    HouseLockFrozenLog houseLockFrozenLog = new HouseLockFrozenLog();
                    houseLockFrozenLog.setType(1);// 操作类型: 0:解冻 1:冻结
                    houseLockFrozenLog.setLockId(lockId);// 智能锁绑定id
                    houseLockFrozenLog.setHouseId(smartLock.getHouseId()); // 公租房id
                    houseLockFrozenLog.setLockAuditId(lockAuthId); // 授权信息id
                    houseLockFrozenLog.setOperationId(userId); // 冻结操作人
                    houseLockFrozenLog.setOperationTime(new Date()); // 操作时间
                    houseLockFrozenLog.setOperationState(1); // 操作时间
                    houseLockFrozenLogRepository.save(houseLockFrozenLog);


                    /**
                     * 产生智能锁冻结/解冻待办事项
                     */
                    addBacklogItem(auth.getMobile(), reason, 0, smartLock.getHouseId(), auth.getAuthorUserId(), userId, enterpriseId);

                    // 操作成功设置缓存，防止重复操作
                    redisTemplate.opsForValue().set("lock_p_id:" + lockId + lockAuthId, "", 1, TimeUnit.MINUTES);
                }
            }

        }
        // 更新亚略特智能锁状态
        yltUpdateLockStatus(smartLock, 1);

        // 更新锁授权人数
        updateOauthNumber(smartLock.getBrandId(), lockId);

        return ResultBean.successfulResult(null);
    }

    /**
     * 统一授权密码
     *
     * @param accessToken
     * @param @param      unifyAuthPwdVo 统一授权密码实体类
     * @return
     */
    public ResultBean<Object> unifyAuthPwd(String accessToken, UnifyAuthPwdVo unifyAuthPwdVo) {
        try {
            if (accessToken == null) {
                return ResultBean.failedResultOfToken();
            }
            if (unifyAuthPwdVo.getAuthType() == null) {
                return ResultBean.failedResultOfParamWithMsg("授权方式不存在");
            }
            if (unifyAuthPwdVo.getHouseIdList().size() == 0) {
                return ResultBean.failedResultOfParamWithMsg("房屋Id不能为空");
            }
            if (unifyAuthPwdVo.getPassword() == null) {
                return ResultBean.failedResultOfParamWithMsg("授权密码不能为空");
            }
            List<String> houseIdList = unifyAuthPwdVo.getHouseIdList();
            Integer authType = unifyAuthPwdVo.getAuthType();
            Integer value = unifyAuthPwdVo.getValue();
            String password = unifyAuthPwdVo.getPassword();
            int length = password.length();
            if (length != 6) {
                return ResultBean.failedResultOfParamWithMsg("授权密码只能是6位数字");
            }
            for (String houseId : houseIdList) {
                List<House> byIdAndStatus = houseRepository.findByIdAndStatus(houseId, 1);
                if (!byIdAndStatus.isEmpty()) {
                    List<SmartLock> smartLocks = smartLockRepository.findByHouseId(houseId);
                    if (smartLocks.isEmpty()) {
                        return ResultBean.failedResultWithMsg("智能锁不存在");
                    }
                    SmartLock smartLock = smartLocks.get(0);
                    String mac = smartLock.getMac();
                    String sn = smartLock.getSn();
                    if (StringUtils.isBlank(sn)) {
                        ResultBean<String> resultBean = smartLockBrandService.getSnByMac(mac, smartLock.getHouseId(),
                                smartLock.getBrandId());
                        if (resultBean == null) {
                            return ResultBean.failedResultOfParamWithMsg("智能锁ID为空, 已重新注册, 稍后重试");
                        }
                        String resultSn = resultBean.getResultData();
                        if (StringUtils.isBlank(resultSn)) {
                            return ResultBean.failedResultWithMsg("设备状态异常");
                        } else {
                            smartLock.setSn(resultSn);
                            smartLock.setMechineStatus(1);
                            smartLockRepository.save(smartLock);
                        }
                    }
                    Long lockId = smartLock.getId();
                    List<SmartLockAuth> byLockId = smartLockAuthRepository.findByLockId(lockId);
                    Long lockAuthId = null;
                    SmartLockAuth smartLockAuth = null;
                    if (!byLockId.isEmpty()) {
                        lockAuthId = byLockId.get(0).getId();
                        Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
                        if (!authOpt.isPresent()) {
                            return ResultBean.failedResultWithMsg("用户授权明细不存在");
                        }
                        smartLockAuth = authOpt.get();
                    }
                    /**
                     * 验证智能锁，或者 密码， 指纹 身份证 CPU卡  蓝牙 是否冻结
                     * true  代表未冻结
                     * false  代表已冻结
                     * @param lockId 智能锁id
                     * @param lockAuthId 用户授权id
                     */
                    Boolean FreezeBoolean = lockCurrencyService.freezeOrNot(lockId, lockAuthId);
                    if (!FreezeBoolean) {
                        return ResultBean.failedResultWithMsg("授权失败，智能锁已冻结或授权已冻结！");
                    }

                    SmartLockPwd smartLockPwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
                    if (smartLockPwd == null) {// 新增
                        smartLockPwd = new SmartLockPwd();
                        smartLockPwd.setLockAuthId(lockAuthId);
                        smartLockPwd.setLockId(lockId);
                        smartLockPwd.setCreateTime(new Date());
                        smartLockPwd.setLastUpdateTime(smartLockPwd.getCreateTime());

                        // 密码序号
                        List<SmartLockPwd> smartLockPwds = smartLockPwdRepository.findByLockId(lockId);
                        if (smartLockPwds != null && !smartLockPwds.isEmpty()) {// 已存在序号
                            List<Integer> indexs = smartLockPwds.stream().filter(vo -> vo.getPwdIndex() != null)
                                    .map(SmartLockPwd::getPwdIndex).distinct().collect(Collectors.toList());
                            Integer max = Collections.max(indexs);
                            if (max == 49) {
                                // 排除已有序号，取1-49间的最小值
                                List<Integer> list = new ArrayList<>();
                                for (int i = 0, j = 49; i < j; ++i) {
                                    list.add(i + 1);
                                }
                                for (Integer i : indexs) {
                                    list.remove(i);
                                }
                                Integer min = Collections.min(list);
                                smartLockPwd.setPwdIndex(min);
                            } else {
                                smartLockPwd.setPwdIndex(max + 1);// 取智能锁密码序号最大值 +1
                            }
                        } else {// 没有序号
                            smartLockPwd.setPwdIndex(1);
                        }
                    } else {// 修改
                        smartLockPwd.setLastUpdateTime(new Date());
                    }

                    smartLockPwd.setType(1);
                    smartLockPwd.setAuthType(authType);
                    smartLockPwd.setAuthTime(new Date());
                    smartLockPwd.setStatus(0);// 0待执行
                    if (smartLock.getBrandId() == 3L) {
                        smartLockPwd.setStatus(1);
                    }
                    smartLockPwd.setPassword(password);


                    // 密码设置方式
                    if (authType == 1) {// 永久
                        smartLockPwd.setStartTime(new Date());
                        String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                        smartLockPwd.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                        smartLockPwd.setLimitDay(DateUtils.daysBetween(smartLockPwd.getStartTime(), smartLockPwd.getEndTime()));
                    } else if (authType == 2) {// 时间期限
                        smartLockPwd.setStartTime(new Date());
                        String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                        smartLockPwd.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                        smartLockPwd.setLimitDay(value);
                    } else if (authType == 3) {// 次数
                        smartLockPwd.setStartTime(new Date());
                        String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                        smartLockPwd.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                        smartLockPwd.setLimitDay(DateUtils.daysBetween(smartLockPwd.getStartTime(), smartLockPwd.getEndTime()));
                        smartLockPwd.setAuthorNumber(value);
                        smartLockPwd.setTimes(value);
                    }

                    // 硬件接口
                    SmartLockVO smartLockVO = new SmartLockVO();
                    smartLockVO.setSn(smartLock.getSn());
                    smartLockVO.setStartTime(DateUtils.format(smartLockPwd.getStartTime(), DateUtils.FORMAT_14));
                    smartLockVO.setEndTime(DateUtils.format(smartLockPwd.getEndTime(), DateUtils.FORMAT_14));
                    if (smartLock.getBrandId() == 3L) {// 亚略特
                        smartLockVO.setStartTime(DateUtils.format(smartLockPwd.getStartTime(), DateUtils.FORMAT_DATETIME_14));
                        smartLockVO.setEndTime(DateUtils.format(smartLockPwd.getEndTime(), DateUtils.FORMAT_DATETIME_14));
                    }
                    smartLockVO.setPassword(smartLockPwd.getPassword());
                    if (authType == 1 || authType == 2) {
                        smartLockVO.setAuthType("2");
                    } else if (authType == 3) {
                        smartLockVO.setAuthType("5");
                        smartLockVO.setTimes(smartLockPwd.getTimes());
                    }
                    smartLockVO.setIndex(smartLockPwd.getPwdIndex());
                    smartLockVO.setDevMac(smartLock.getMac());
                    smartLockVO.setAuthInfoId(lockAuthId);
                    smartLockVO.setIndexNum(smartLockPwd.getPwdIndexNum());
                    // 熙照
                    if (authType == 3) {
                        smartLockVO.setTimes(value);
                    } else {
                        smartLockVO.setTimes(-1);
                    }

                    // 亚略特
                    if (smartLock.getBrandId() == 3L) {
                        if (smartLockPwdRepository.findByLockAuthId(lockAuthId) == null) {// 新增
                            smartLockPwd.setfAppUserId(GenerateNiceString.generateNiceString());
                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                            yltVO.setfLockMAC(smartLock.getMac());
                            yltVO.setfAppUserID(smartLockPwd.getfAppUserId());
                            yltVO.setfBeginDate(smartLockVO.getStartTime());
                            yltVO.setfEndDate(smartLockVO.getEndTime());
                            yltVO.setfOpenByPassword(1);
                            yltVO.setfOpenByIDCard(0);
                            yltVO.setfOpenByBLE(0);
                            yltVO.setfOpenByFinger(0);
                            yltVO.setfOpenByICCard(0);
                            yltVO.setfOpenPassword(smartLockPwd.getPassword());
                            smartLockVO.setYltAuth(yltVO);
                        } else {// 修改
                            smartLockVO.setfAuthorizationID(smartLockPwd.getfAuthorizationId());
                        }
                    }
                    ResultBean<String> stringResultBean = smartLockBrandService.operationPassword(smartLockVO, smartLockPwd,
                            smartLock.getBrandId());
                    String resultData = stringResultBean.getResultData();
                    String msg = stringResultBean.getMsg();
                    String code = stringResultBean.getCode();
                    if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                        log.error("LockAppService authPwd---> " + msg);
                        return ResultBean.failedResultWithCodeAndMsg(code, msg);
                    } else {
                        log.info("LockAppService authPwd---> callBack={}", resultData);
                        // 生成密码授权明细
                        if (smartLock.getBrandId() == 3L && smartLockPwdRepository.findByLockAuthId(lockAuthId) == null) {// 亚略特 新增
                            smartLockPwd.setfAuthorizationId(resultData);
                        }
                        if (smartLock.getBrandId() == 5L) {
                            smartLockPwd.setIdentification(resultData);
                        }
                        if (smartLock.getBrandId() == 6L) {
                            Long id = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
                            smartLockPwd.setReturnPwdId(id);
                        }
                        if (smartLock.getBrandId() == 8L) {
                            String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                            smartLockPwd.setIdentification(phoneNo);
                            String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                            smartLockPwd.setfAuthorizationId(keyId);
                        }
                        smartLockPwdRepository.save(smartLockPwd);
                        // 更新用户授权明细状态
                        updateSmartLockAuthStatus(smartLock.getBrandId(), 1, 1, smartLockAuth);
                        // 更新锁授权人数
                        updateOauthNumber(smartLock.getBrandId(), lockId);
                    }
                }
            }
            return ResultBean.successfulResult("授权成功！");
        } catch (Exception e) {
            log.error("LockAppService authPwd Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }

    }

    /**
     * 获取蓝牙密钥
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  锁授权id
     * @return
     */
    public ResultBean<Object> BluetoothKey(String accessToken, Long lockAuthId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            SmartLockBle byLockAuthId = smartLockBleRepository.findByLockAuthId(lockAuthId);
            if (ObjectUtil.isEmpty(byLockAuthId)) {
                return ResultBean.failedResultOfParamWithMsg("没有进行蓝牙授权");
            }
            Optional<SmartLock> smartLock = smartLockRepository.findById(byLockAuthId.getLockId());

            ResultBean<String> bluetoothUnlocking = smartLockBrandService.BluetoothKey(lockAuthId,smartLock.get().getBrandId(),smartLock.get().getSn());
            String msg = bluetoothUnlocking.getMsg();
            String code = bluetoothUnlocking.getCode();
            String resultData = bluetoothUnlocking.getResultData();
            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authBle---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                return ResultBean.successfulResult(JSON.parseObject(resultData));
            }
            // String mac = smartLockAuthRepository.BluetoothKey(lockAuthId);
            // Map<String, Object> maps = new HashMap<>();
            // maps.put("deviceNum", mac);
            // maps.put("identification", "L16835173200995781");
            // String s = HttpUtils.httpClientGet("https://paas.locksuiyi.com/deviceManagement/api/bluetooth/unlockKey.do", redisService.getToken(), maps);
            // return ResultBean.successfulResult(JSON.parseObject(s));
        } catch (Exception e) {
            log.error("密钥获取失败" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 天网互联蓝牙解密
     *
     * @param accessToken 权限鉴定
     * @param decryptInfo 密钥
     * @return
     */
    public ResultBean<Object> deciphering(String accessToken, String decryptInfo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("decryptInfo", decryptInfo);
            String deciphering = HttpUtils.httpClientPost("https://paas.locksuiyi.com/deviceManagement/api/aesDecrypt.do", JSON.toJSONString(map), redisService.getToken());
            return ResultBean.successfulResult(JSON.parseObject(deciphering));
        } catch (Exception e) {
            log.error("解密失败" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 授权四代智能锁临时密码
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  授权用户id
     * @param lockId      智能锁id
     * @return
     */
    public ResultBean<Object> authorizationTemporaryPwd(String accessToken, Long lockAuthId, Long lockId) {
        return ResultBean.successfulResult("授权成功");
    }


    /**
     * 授权人脸
     *
     * @param accessToken
     * @return
     */
    @Transactional
    public ResultBean<Object> authFace(String accessToken, SmartLockFace smartLockFace) {
        log.info(
                "LockAppService authFingerprint, accessToken={}, lockAuthId={}, lockId={}, type{}, fingerprint={}, authType={}, value={}",
                accessToken, smartLockFace.getLockAuthId(), smartLockFace.getLockId(), smartLockFace.getAuthType(), smartLockFace.getValue(), smartLockFace.getFaceImage());
        try {
            Long lockAuthId = smartLockFace.getLockAuthId();
            Long lockId = smartLockFace.getLockId();
            Integer authType = smartLockFace.getAuthType();
            Integer value = smartLockFace.getValue();
            String faceImage = smartLockFace.getFaceImage();
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }
            if (authType == null) {
                return ResultBean.failedResultOfParamWithMsg("授权方式不存在");
            }
            if (StrUtil.isEmpty(faceImage)) {
                return ResultBean.failedResultOfParamWithMsg("请上传图片");
            }
            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockFace face = smartLockFaceRepository.findByLockAuthId(lockAuthId);
            if (ObjectUtil.isNotEmpty(face)) {
                return ResultBean.failedResultWithMsg("该用户已经授权人脸");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }

            // 授权前更新未激活智能锁sn值
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            if (smartLock.getMechineStatus().equals(2)) {
                return ResultBean.failedResultWithMsg("智能锁已冻结！");
            }
            smartLock.setMechineStatus(1);
            smartLockRepository.save(smartLock);

            /**
             * 验证智能锁，或者 密码， 指纹 身份证 CPU卡  蓝牙 是否冻结
             * true  代表未冻结
             * false  代表已冻结
             * @param lockId 智能锁id
             * @param lockAuthId 用户授权id
             */
            Boolean FreezeBoolean = lockCurrencyService.freezeOrNot(lockId, lockAuthId);
            if (!FreezeBoolean) {
                return ResultBean.failedResultWithMsg("授权失败，智能锁已冻结或授权已冻结！");
            }

            SmartLockFace smartLockFace1 = smartLockFaceRepository.findByLockAuthId(lockAuthId);
            if (ObjectUtil.isNull(smartLockFace1)) {// 新增
                SmartLockFace newSmartlockface = new SmartLockFace();
                newSmartlockface.setLockAuthId(lockAuthId);
                newSmartlockface.setLockId(lockId);
                newSmartlockface.setCreateTime(new Date());
                newSmartlockface.setAuthType(authType);
                newSmartlockface.setStatus(1);// 0待执行
                newSmartlockface.setFaceImage(faceImage);
                newSmartlockface.setSn(smartLock.getSn());
                // 密码设置方式
                if (authType == 2) {// 时间期限
                    if (value == null) {
                        return ResultBean.failedResultOfParamWithMsg("请填写授权天数");
                    }
                    newSmartlockface.setStartTime(new Date());
                    String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                    newSmartlockface.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                    newSmartlockface.setLimitDay(value);
                }


                /**
                 * 调厂商接口授权人脸
                 */
                ResultBean<String> stringResultBean = smartLockBrandService.operationFace(newSmartlockface, smartLock.getBrandId());
                String resultData = stringResultBean.getResultData();
                String msg = stringResultBean.getMsg();
                String code = stringResultBean.getCode();
                if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    log.error("LockAppService authPwd---> " + msg);
                    return ResultBean.failedResultWithCodeAndMsg(code, msg);
                } else {
                    if (smartLock.getBrandId() == 8L) {
                        String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                        newSmartlockface.setIdentification(phoneNo);
                        String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                        newSmartlockface.setKeyId(keyId);
                    } else {
                        newSmartlockface.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
                        newSmartlockface.setIdentification(resultData);
                    }
                    smartLockFaceRepository.save(newSmartlockface);

                    // 更新用户授权明细状态
                    updateSmartLockAuthStatus(smartLock.getBrandId(), 6, 1, smartLockAuth);
                    // 更新锁授权人数
                    updateOauthNumber(smartLock.getBrandId(), lockId);
                    return ResultBean.successfulResultWithMsg("指令下发成功", null);

                }

            } else {
                smartLockFace1.setFaceImage(faceImage);
                // 密码设置方式
                if (authType == 2) {// 时间期限
                    if (value == null) {
                        return ResultBean.failedResultOfParamWithMsg("请填写授权天数");
                    }
                    smartLockFace1.setStartTime(new Date());
                    String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                    smartLockFace1.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                    smartLockFace1.setLimitDay(value);
                }


                /**
                 * 调厂商接口授权人脸
                 */
                smartLockFace1.setSn(smartLock.getSn());
                ResultBean<String> stringResultBean = smartLockBrandService.updateFace(smartLockFace1, smartLock.getBrandId());
                String resultData = stringResultBean.getResultData();
                String msg = stringResultBean.getMsg();
                String code = stringResultBean.getCode();
                if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    log.error("LockAppService authPwd---> " + msg);
                    return ResultBean.failedResultWithCodeAndMsg(code, msg);
                } else {
                    if (smartLock.getBrandId() == 8L) {
                        String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                        smartLockFace1.setIdentification(phoneNo);
                        String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                        smartLockFace1.setKeyId(keyId);
                    }
                    smartLockFaceRepository.save(smartLockFace1);
                    return ResultBean.successfulResultWithMsg("指令下发成功", null);

                }
            }
        } catch (Exception e) {
            log.error("LockAppService authFingerprint Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 查看人脸授权
     *
     * @param accessToken 权限鉴定
     * @param lockAuthId  锁授权id
     * @return
     */
    public ResultBean<Object> findFace(String accessToken, Long lockAuthId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }

            SmartLockFace smartLockFace = smartLockFaceRepository.findByLockAuthId(lockAuthId);

            if (ObjectUtil.isNull(smartLockFace)) {
                return ResultBean.successfulResultWithMsg("智能锁人脸未授权", null);
            } else {
                return ResultBean.successfulResult(smartLockFace);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 删除授权人脸信息
     *
     * @param accessToken 权限鉴定
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ResultBean<Object> deleteFace(String accessToken, SmartLockFace smartLockFace) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            Long lockAuthId = smartLockFace.getLockAuthId();
            Long lockId = smartLockFace.getLockId();
            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            SmartLockFace smartlockFace1 = smartLockFaceRepository.findByLockAuthId(lockAuthId);
            if (smartlockFace1 == null) {
                return ResultBean.failedResultWithMsg("密码授权明细不存在");
            }


            smartlockFace1.setSn(smartLock.getSn());
            // 调厂商删除授权人脸信息
            ResultBean<String> stringResultBean = smartLockBrandService.clearFace(smartlockFace1, smartLock.getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService deletePwdAuth---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockAppService deletePwdAuth---> callBack={}", resultData);
                smartLockFaceRepository.deleteByLockAuthId(lockAuthId);

//                ossService.deleteObject("",smartlockFace1.getFaceImage().split("https://xj-saas-images.oss-cn-qingdao.aliyuncs.com/")[1]);

                // 更新用户授权明细状态
                updateSmartLockAuthStatus(smartLock.getBrandId(), 6, 2, smartLockAuth);
                // 更新锁授权人数
                updateOauthNumber(smartLock.getBrandId(), lockId);

                return ResultBean.successfulResultWithMsg("删除成功", null);
            }
        } catch (Exception e) {
            log.error("LockAppService deletePwdAuth Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 公寓授权人脸
     *
     * @return
     */
    public String authApartmentFace(String accessToken, String orderId) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        String phone = token.getPhone();
        AppUser appUser = appUserRepository.findByPhoneAndStatusAndType(phone, 1, UserLoginTypeEnum.PROGRAM.getValue());
        // String userId = token.getId();
        // AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
        if (appUser == null) {
            throw new RuntimeException("用户信息不存在");
        }
        if (appUser.getCertificationStatus() == 0) {
            throw new RuntimeException("请先进行实名认证");
        }

        Order order = iOrderService.selectOrderById(orderId);
        String houseId = order.getHouseId();
        String mobile = appUser.getPhone();
        List<SmartLock> smartLocks = smartLockRepository.findByHouseId(houseId);
        if (CollectionUtil.isEmpty(smartLocks)) {
            throw new RuntimeException("没有智能锁信息");
        }

        if (smartLocks.get(0).getBrandId() == 5 || smartLocks.get(0).getBrandId() == 6) {

            SmartLockAuth byHouseIdAndMobile = smartLockAuthRepository.findByHouseIdAndMobile(houseId, mobile);
            if (byHouseIdAndMobile == null) {
                throw new RuntimeException("智能锁授权未找到");
            }
            Long lockAuthId = byHouseIdAndMobile.getId();
            Long lockId = byHouseIdAndMobile.getLockId();
            SmartLockFace byLockAuthId = smartLockFaceRepository.findByLockAuthId(lockAuthId);
            if (ObjectUtil.isNotNull(byLockAuthId)) {
                throw new RuntimeException("已经授权人脸信息");
            }
            String facePic = ossBucketUrl + appUser.getFacePic();
            String sn = smartLocks.get(0).getSn();
            SmartLockFace smartLockFace = new SmartLockFace();
            smartLockFace.setSn(sn);
            smartLockFace.setFaceImage(facePic);
            smartLockFace.setAuthType(SmartLockFace.PERMANENT_FLAG_YES);
            smartLockFace.setLockId(lockId);
            smartLockFace.setLockAuthId(lockAuthId);
            ResultBean<String> stringResultBean = smartLockBrandService.operationFace(smartLockFace, smartLocks.get(0).getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();
            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authPwd---> " + msg);
                throw new RuntimeException(msg);
            }

            // Long returnFaceId = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
            // smartLockFace.setReturnFaceId(returnFaceId);
            if (smartLocks.get(0).getBrandId() == 8L) {
                String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                smartLockFace.setIdentification(phoneNo);
                String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                smartLockFace.setKeyId(keyId);
            } else {
                smartLockFace.setIdentification(resultData);
                smartLockFace.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
            }
            smartLockFace.setStatus(1);
            smartLockFace.setCreateTime(new Date());
            smartLockFaceRepository.save(smartLockFace);
            SmartLock smartLock = smartLocks.get(0);
            smartLock.setMechineStatus(1);
            smartLockRepository.save(smartLock);
            this.updateOauthNumber(smartLock.getBrandId(), smartLock.getId());
            byHouseIdAndMobile.setFaceStatus(1);
            smartLockAuthRepository.save(byHouseIdAndMobile);
        } else {
            throw new RuntimeException("该智能锁没有人脸开锁");
        }
        return "授权成功";
    }


    /**
     * 嗨小克小程序授权人脸
     *
     * @param accessToken 权限鉴定
     * @param houseId     房屋id
     * @return
     */
    public ResultBean<Object> authorizationFace(String accessToken, String houseId) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        String phone = token.getPhone();
        AppUser appUser = appUserRepository.findByPhoneAndStatusAndType(phone, 1, UserLoginTypeEnum.CONSUMER.getValue());
        if (appUser == null) {
            return ResultBean.failedResultWithMsg("用户信息不存在");
        }
        if (appUser.getCertificationStatus() == 0) {
            return ResultBean.failedResultWithMsg("请先进行实名认证");
        }

        // 如果是合租的子房子，拿父房子的houseId
        List<House> houseList = houseRepository.findByIdAndStatus(houseId, 1);
        if (CollectionUtil.isNotEmpty(houseList)) {
            String housemateId = houseList.get(0).getHousemateId();
            if (StrUtil.isNotEmpty(housemateId)) {
                houseId = housemateId;
            }
        }

        String mobile = appUser.getPhone();
        List<SmartLock> smartLocks = smartLockRepository.findByHouseId(houseId);
        if (CollectionUtil.isEmpty(smartLocks)) {
            return ResultBean.failedResultWithMsg("没有智能锁信息");
        }
        if (smartLocks.get(0).getMechineStatus() == 2) {
            return ResultBean.failedResultWithMsg("智能锁已冻结");
        }

        // 判断是否是6代智能锁、五代锁
        if (smartLocks.get(0).getBrandId() == 6 || smartLocks.get(0).getBrandId() == 5 || smartLocks.get(0).getBrandId() == 7 || smartLocks.get(0).getBrandId() == 8) {

            SmartLockAuth smartLockAuth = smartLockAuthRepository.findByHouseIdAndMobile(houseId, mobile);
            if (smartLockAuth == null) {
                return ResultBean.failedResultWithMsg("智能锁授权未找到");
            }
            Long lockAuthId = smartLockAuth.getId();
            Long lockId = smartLockAuth.getLockId();
            SmartLockFace byLockAuthId = smartLockFaceRepository.findByLockAuthId(lockAuthId);
            if (ObjectUtil.isNotNull(byLockAuthId)) {
                return ResultBean.failedResultWithMsg("已经授权人脸信息");
            }

            String facePic = ossBucketUrl + appUser.getFacePic();
            String sn = smartLocks.get(0).getSn();
            SmartLockFace smartLockFace = new SmartLockFace();
            smartLockFace.setSn(sn);
            smartLockFace.setFaceImage(facePic);
            smartLockFace.setAuthType(SmartLockFace.PERMANENT_FLAG_YES);
            smartLockFace.setLockId(lockId);
            smartLockFace.setLockAuthId(lockAuthId);
            ResultBean<String> stringResultBean = smartLockBrandService.operationFace(smartLockFace, smartLocks.get(0).getBrandId());
            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();
            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                log.error("LockAppService authPwd---> " + msg);
                return ResultBean.failedResultWithMsg(msg);
            }

            // Long returnFaceId = (Long) JSONObject.parseObject(resultData).getJSONObject("data").get("id");
            // smartLockFace.setReturnFaceId(returnFaceId);
            if (smartLocks.get(0).getBrandId() == 8L) {
                String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                smartLockFace.setIdentification(phoneNo);
                String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                smartLockFace.setKeyId(keyId);
            } else {
                smartLockFace.setIdentification(resultData);
                smartLockFace.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
            }
            smartLockFace.setStatus(1);
            smartLockFace.setCreateTime(new Date());
            smartLockFaceRepository.save(smartLockFace);
            SmartLock smartLock = smartLocks.get(0);
            smartLock.setMechineStatus(1);
            smartLockRepository.save(smartLock);
            smartLockAuth.setFaceStatus(1);
            smartLockAuthRepository.save(smartLockAuth);
            this.updateOauthNumber(smartLock.getBrandId(), smartLock.getId());

        } else {
            return ResultBean.failedResultWithMsg("该智能锁没有人脸开锁");
        }
        return ResultBean.successfulResultWithMsg("授权成功", null);
    }

    public List<Date> getLatelyTenMinsTimeslot(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, (calendar.get(Calendar.MINUTE))/10*10);
        calendar.set(Calendar.SECOND,0);
        Date early = calendar.getTime();
        calendar.add(Calendar.MINUTE, 10);
        Date late = calendar.getTime();
       /* return Arrays.asList(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(early),
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(late));*/
        return Arrays.asList(early,late);
    }

    /**
     * 申请五代锁离线密码（替换小程序申请临时密码）
     * @param accessToken
     * @param lockId
     * @param lockAuthId
     * @return
     */
    public ResultBean<Object> authOfflinePwd(String accessToken, Long lockId, Long lockAuthId) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            String userId = token.getId();
            AppUser user = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
            if (user == null) {
                return ResultBean.failedResultOfParamWithMsg("用户信息不存在");
            }

            if (lockAuthId == null) {
                return ResultBean.failedResultOfParamWithMsg("用户授权id不存在");
            }

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }


            Optional<SmartLock> byId = smartLockRepository.findById(lockId);
            SmartLock smartLock = byId.get();
            if (!byId.isPresent()) {
                return ResultBean.failedResultOfParamWithMsg("锁安装信息未找到");
            }

            // 锁冻结不给申请
            if (smartLock.getMechineStatus().equals(2)) {
                return ResultBean.failedResultOfParamWithMsg("智能锁已被冻结");
            }

            Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(lockAuthId);
            if (!authOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("用户授权明细不存在");
            }
            SmartLockAuth smartLockAuth = authOpt.get();

            Optional<House> houseOptional = houseRepository.findById(smartLockAuth.getHouseId());
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("房屋不存在");
            }


            Integer authorNumber = 5;
            Integer useNumber = 0;
            Integer passwordValidity = 1;
            // 查询房屋临时密码次数
            String sql = "SELECT * FROM m_match_user_lock_author WHERE house_id = ?";
            List<MatchUserLockAuthor> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MatchUserLockAuthor.class), smartLock.getHouseId());
            MatchUserLockAuthor entity = null;
            // 有设置记录
            if (!list.isEmpty()) {
                entity = list.get(0);
                // 申请使用次数
                authorNumber = entity.getAuthorNumber();
                // 有效期天数
                passwordValidity = entity.getPasswordValidity();
                // 使用次数
                useNumber = entity.getUseNumber();
            } else {
                entity = new MatchUserLockAuthor();
                // 默认5次
                entity.setAuthorNumber(authorNumber);
                // 查询承租人库数据
                List<MatchUserHouse> hList = matchUserHouseRepository.findByHouseId(smartLock.getHouseId());
                if (!hList.isEmpty()) {
                    entity.setMatchUserStockId(hList.get(0).getMatchUserStockId());
                } else {
                    log.error("临时密码授权, 房屋承租人库数据未找到, houseId={}", smartLock.getHouseId());
                }
                entity.setOperatorUserId(1l);
                entity.setUseNumber(useNumber);
                entity.setPasswordValidity(passwordValidity);
                entity.setCreateTime(new Date());
                String date = DateUtils.format(new Date(), DateUtils.FORMAT_6);
                entity.setEffectiveJulyDate(date);
                entity.setLastUpdateTime(new Date());
                entity.setHouseId(smartLock.getHouseId());
                matchUserLockAuthorRepository.save(entity);
            }

            // 承租人，判断剩余可用次数
            if (authorNumber - useNumber > 0) {
//                ResultBean<Object> objectResultBean = authPwd(accessToken, lockAuthId, lockId, 2, null, 2, passwordValidity);
                SmartLockVO vo = new SmartLockVO();
                vo.setSn(smartLock.getMac());
                ResultBean<Object> objectResultBean = smartLockBrandService.offlinePwd(vo, smartLock.getBrandId());
                if (objectResultBean != null && objectResultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    entity.setUseNumber(entity.getUseNumber() + 1);
                    entity.setLastUpdateTime(new Date());
                    List<Date> latelyTenMinsTimeslot = this.getLatelyTenMinsTimeslot();
                    MatchUserLockAuthorVO authorVO = new MatchUserLockAuthorVO();
                    authorVO.setUseNumber(entity.getUseNumber() + 1);
                    authorVO.setStartValidTime(latelyTenMinsTimeslot.get(0));
                    authorVO.setEndValidTime(latelyTenMinsTimeslot.get(1));
                    authorVO.setPassword(String.valueOf(objectResultBean.getResultData()));
                    authorVO.setAuthorNumber(authorNumber);
                    matchUserLockAuthorRepository.save(entity);
                    return ResultBean.successfulResult(authorVO);
                } else {
                    // 授权失败
                    return objectResultBean;
                }
            } else {
                return ResultBean.failedResultOfParamWithMsg("授权次数已达上限");
            }
        } catch (Exception e) {
            log.error("申请离线密码异常：{}",e.getMessage(), e);
            return ResultBean.failedResultWithMsg(e.getMessage());
        }
    }
}
